Fix CORS in Angular 8: Using CLI proxy configuration

Alex Ssanya
2 min readNov 23, 2019

In this writing, I am going to share on how you can fix the CORS error in Angular 8 (these steps can work for any other Angular 2+). But before we get started, let us get to understand what CORS is.

What is CORS?

CORS (Cross-Origin Resource Sharing) is a system, consisting of transmitting HTTP headers, that determines whether browsers block frontend JavaScript code from accessing responses for cross-origin requests.

CORS enables the webserver to decide how its resources can be accessed by servers at a different origin.

By default, the browsers disable apps from making cross-domain requests except if the HTTP response has a Control-Allow-Origin header with a * value or the domain of the client app. So in cases when the backend server is not well configured, you may suffer the CORS error.

Fixing the CORS Error

There are 2 ways to do so:-

  1. if you own the backend server, it would be best to configure the backend server to return the appropriate CORS HTTP headers
  2. Configure Angular CLI Proxy which is our focus in this article.

Angular CLI proxy

Here, I am assuming you have an angular project with some services making HTTP requests.

  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 and you are done.

FYI: You may also you this trick as a security measure to hide the server requests you making from being displayed in the browser.

References

Happy Coding :)

--

--