maybe I didn't quite understand proxys yet, but I have my server backend on localhost:7000 and my frontend client on localhost:3000.
Now I configured a proxy in my frontend package.json:
"proxy": "http://127.0.0.1:7000"
. This avoided the cors installation in the backend and accepted requests to my server. How does that work or why is it avoiding the cors configuration? And whats the difference then between the proxy and cors?
CodePudding user response:
CORS errors occur up due to the same-origin policy that is implemented in most browsers. More specifically the reason you are getting the error is because you’re making a request to a different origin from the one you’re currently on. In your case that's your frontend running on http://localhost:3000
which is trying to access the backend on http://localhost:7000
In order to fix this, you could change your backend to send the Access-Control-Allow-Origin
response header where you include the frontend's origin - or... you use a proxy.
The Proxy basically attempts to fool the browser by pretending to have your backend on the same origin localhost:3000
whereas underneath the hood it's accessing the resource from the actual origin localhost:7000
.
You can read this article which explains it in further detail.