React proxy does not work even though config is set properly

Viewed 4562

I have tried multiple things

I added

"proxy": "http://localhost:5000/"

to package.json, and even

devServer: {
    historyApiFallback: true,
     proxy: {
     "/": "http://localhost:5000"
     }
  }

to webpack.config.dev.js

However, none of these seem to work. When I go to localhost:3000/age (one of my routes), the backend does not receive any request even though the React component is tied to it AND I have the proxy set in package.json

My express app listens on route 5000, and I am visiting it through my browser as localhost:3000/age and also have tried localhost:5000/age but don't work

2 Answers

You need to set your proxy your backend's port. If your backend is listening on 5000 then it should be "proxy": "http://localhost:5000"

By default any http requests in react to a sites own domain use whatever port the app is running on. Since react is running on 5000 itll send all requests through that port. The proxy tells it to change this default behavior to the specified proxy.

Check this documentation enter image description here

The development server will only attempt to send requests without text/html in its Accept header to the proxy.

If you access directly on browser. its set content type header as text/html .So its not working . Better use only for an ajax/fetch request .

issue

for development react have own server.if you need a react side route better try react-router. After the production build its working same as you expect

Related