Avoiding CORS Errors on Localhost (in 2020)
When developing a website/web app on localhost which makes requests to another server, you might run into Cross Origin Resource Sharing (CORS) issues. I won’t go into too much detail about what CORS is in this post. All I will say is that CORS exists for security reasons, but when you’re developing locally it can be a pain! You can read more about CORS on the MDN docs.
I have written this simple guide to explain the main solutions for disabling cross origin restrictions on localhost (and therefore fixing any CORS errors whilst developing your app locally), which I will explain in more detail below.
1. Use the proxy setting in Create React App
Create React App comes with a config setting which allows you to simply proxy API requests in development. This is available in react-scripts@0.2.3
. To do this add the proxy setting to your package.json like this
"proxy": "https://cat-fact.herokuapp.com/",
Now when you make an API request to https://localhost:3000/api/facts
Create React App will proxy the API request to https://cat-fact.herokuapp.com/facts
and the CORS error will be resolved.
This is a really simple solution which might not work with more complicated situations where multiple API’s are involved, or certain types of API authentication is needed.