0

I see that the request sent from the ui created using React is forwarded to the backend, but I can't get the response from the ui. There may be details that I missed as I am very new to these issues, thanks in advance :)

//react Login.js
function Login() {
  const fetch = actions.fetchUser();
  async function handleSubmit() {
    try {
      fetch();
    } catch (err) {
      console.error('err', err);
    }
}
export default Login;

//index.js
import axios from 'axios';
export const fetchUser = () => async () => {
  await axios.get('/api/login');
};

//setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
  app.use(
    ['/api'],
    createProxyMiddleware({
      target: 'http://localhost:5000',
    }),
  );
};

//express app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(bodyParser.json());
require('./routes/login')(app);
    
app.listen(port, () => {
   console.log(`Example app listening on port ${port}`)
})

// espress login.js
module.exports = app => {
app.get('/api/login', (req, res) => {
   console.error('express login');
    res.send('login');
});
aylin
  • 101
  • 10

1 Answers1

0

First of all, do not mix cjs and mjs import/exports. second of all, you export your middleware but never register/use it. At least your code does not show that part.

Here is very minimal example how you can proxy your react UI via express.

const express = require('express');
const proxy = require('express-http-proxy');
const app = express();

app.get('/api', (req, res) => {
  res.send({my: 'data'});
});

// register other routes here

app.use(proxy('http://127.0.0.1:3000'));

app.listen(5000, '0.0.0.0', () => {
  console.log('Server is running at http://127.0.0.1:5000');
});

React app content will be available on http://127.0.0.1:5000 with your routes. And http://127.0.0.1:5000/api will be your express route.

Note: I assume your react app runs on the port 3000

n1md7
  • 2,854
  • 1
  • 12
  • 27
  • Hi @n1md7, thank you for your interest. I know that in the example I wrote, it is not necessary to import the proxy file. When I make a request through react, I can see the log on the login page on the backend, but I can't see the response on the react side. Unfortunately, your solution did not work for me, for example, I could not see the log on the backend side. – aylin Aug 22 '22 at 07:49