In this topic, I am going to explain on how you can fix the CORS error in Angular using CLI proxy configuation or using some changes in chrome setting.
What do you mean by CORS Error?
CORS stands for Cross-Origin Resource Sharing. It is a mechanism (consisting of transmitting HTTP headers) that is used to bypass the same-origin policy so that resources from one origin can access resources from another origin in a secure manner.
CORS enables the webserver to decide how its resources can be accessed by servers at a different origin.
CORS handle request from the external domain of HTTP headers which are as follows
- Access-Control-Allow-Origin
- Access-Control-Allow-Credentials
- Access-Control-Allow-Headers
- Access-Control-Allow-Methods
- Access-Control-Expose-Headers
- Access-Control-Max-Age
- Access-Control-Request-Headers
- Access-Control-Request-Method
How to fix CORS Error?
We can resolve this cors error in two way:
- Using Angular CLI proxy and passing proper CORS headers request on the server-side. – this proper way to handle cors in angular application.
- Using disable CORS origin policy in Chrome cofiguarion – this is easy and fast way.
Using Angular CLI proxy
CLI proxy works as an intermediate between the browser and our web server.
Step 1 : Create the Proxy Configuration File called proxy.conf.json in the root of the src folder
{ "/api": { "target": "http://localhost:3000", "secure": false } }
2. Configure angular.json with proxyConfig key under the architect>serve>options that point to the src/proxy.conf.json as below
"architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-application-name:build", "proxyConfig": "src/proxy.conf.json" },
3. Now, simply run ng serve in your command tool to execute your application.
Using disable CORS origin policy in chrome
For Windows:
- Open the start menu
- Type Windows Key+R or open “Run”
- Execute the following command:
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
For MAC:
- Open the Terminal
- Execute the following command:
open /Applications/Google\ Chrome.app --args --user-data-dir="/var/tmp/Chrome dev session" --disable-web-security