Fixing CORS errors in Angular
What is CORS?
CORS stands for Cross-Origin resource sharing. It is an HTTP header mechanism which allows web browsers to determine the origins from which they are allowed to load resources.
How does CORS work?
When a browser sends a request to another origin than the one it is being hosted on, (cross-origin request), it includes an Origin
header that specifies the origin of the request.
A server that has CORS configured is going to include an Access Control Allow Origin
header in the response. If the content of the header doesn't match the origin, or if CORS is not configured, the browser will block the request as part of its same origin policy.
Where does CORS cause issues for developers?
If you're developing a website and have the frontend running on a different port than the backend, you'll probably need to configure CORS. Here, I am going to cover some solutions that you can put in place in your angular application to avoid facing issues related to CORS.
Configuring proxy
Imagine that your front-end, running on port 4200, wants to fetch a list of items from your backend running on port 3000.
To achieve this, your frontend is going to send an http GET request to localhost:3000/api/v1/items
. However, as we mentioned earlier, this violates the same origin policy on your browser because different ports imply different origins.
Luckily, there is a workaround to deceive the browser into thinking that it is sending the request to localhost:4200/api/v1/items
instead of localhost:3000/api/v1/items
. All you have to do is to set up a proxy server.
A proxy server will act as intermediate between your frontend-application and the api. It will receive the request and then forward it to your api.
Add a proxy.conf.json
file to your project. Your file should contain this code :
{
"/api/*" : {
"target" : "http://localhost:3000/",
"secure" : false,
"pathRewrite" : {
"^/api" : ""
},
"changeOrigin" : true,
"logLevel" : "debug"
}
}
and then, in your angular.json
file add the proxyConfig
key.
"options": {
"proxyConfig" : "src/proxy.conf.json"
}
Add it under the serve options key.
This should solve your CORS errors when you are using angular.