Monday, 5 June 2023

How do you setup a proxy in React?

I am having issues developing a React app. When in development, my the app runs on localhost:3000 and my backend server (which hosts the /api endpoint) runs on localhost:80. The frontend makes calls to localhost:80/api but they fail because of CORS. I tried solving the issue setting up a proxy in my package.json with the following line:

"proxy": "http://localhost:80"

The React docs say that using a proxy "tells the development server to proxy any unknown requests to your API server..." Now for whatever reason, rather than proxying requests for /api to localhost:80, React is signaling a redirect (HTTP 301) to localhost:80. This is causing the CORS errors to still occur.

You can see from this screenshot of the network traffic that the front end is making a request for my /api endpoint and the backend is signaling to redirect: network traffic

The React docs specifically say that using a proxy "avoids CORS issues and error messages" in development, so I expect that I have the correct solution but I am setting it up the wrong way.

Is there a way I can prevent these CORS problems without using a Chrome extension?



from How do you setup a proxy in React?

No comments:

Post a Comment