Trusted answers to developer questions

What is CORS in Angular?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

CORS is an HTTP header- based mechanism that allows the server to indicate any other domain, scheme, or port origins and enables them to be loaded.

Example

Here is an example of a cross-origin request: Front-end at educative.io makes an XMLHttpRequest for educative.io/shot.json

CORS

To prevent attacks on websites, browsers restrict cross-origin HTTP requests from scripts. XMLHttpRequest and Fetch API follow the same-origin policy and can only process requests from the origin where the application was loaded.

CORS in Angular

Here are the few steps needed to fix the CORS issues in Angular to ensure a smooth data transfer between client and server:

Create a Proxy Config file

In your application, reate a proxy.config.json file in the src folder. Open the file and append the following code to allow all the /api/ requests to be redirected to the target hostname:

{
"/api/*": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}

Note:* Depending on your use case, you can set secure to true if you want to use the SSL feature.

Append proxy config key

In your angular.json file, add the following key-value pairs in the “serve -> options” field that points it to your proxy.config.json file:

"architect": {
"serve": {
"builder": ""
"options": {
"proxyConfig": "src/proxy.conf.json"
},
}
}

Run

Finally, you may run the dev server using:

ng serve

RELATED TAGS

angular

CONTRIBUTOR

Fahad Farid
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?