How to avoid CORS error in Angular Development mode

Golap Hazarika
3 min readMay 24, 2022

Access to XMLHttpRequest at ‘${url}’ from origin ‘${origin}’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Let's resolve the issue.

Angular (Front-end) is running on http://localhost:4200 and (Back-end) is running on http://localhost:8000

Let's assume your backend rest GET API is http://localhost:8000/api/v1/getNews

Now how do you access backend rest API in angular without getting CORS error? It's straightforward.

As a developer, we can avoid many ways this CORS error. But we will discuss hear the most efficient one. In this method, we don’t need to modify any backend code. So let's start…

Step 1:

Create a (.json) file in the root directory in angular. I name it proxyconfig.json. You can name it as you want. but make sure it's a (.json) file.

Step 2:

Now open the “package.json” file which is in the root directory of your angular project and add — proxy-config proxyconfig.json after start”: “ng serve”.

start:dev”: “ng serve — proxy-config proxyconfig.json”,

Here we include the proxyconfig.json file in the “package.json” file script part.

Step 3:

Now open the proxyconfig.json file and add these lines as shows in the image.

Let me explain what are these.

You have a rest api which is “http://localhost:8000/api/v1/getNews”. so your target url is “http://localhost:8000/”

When you call this rest api, at that time Angular look into the “proxyconfig.json” file and internelly connect the “http://localhost:8000/” and get the data for you.

Note: If you need to connect multiple Backend or diffrent backend module. example :

Step 4:

Now in your angular service file you need call the api. You do not need to paste the entire rest api in the api call method. just paste the remaining part the api call method.(avoid the target url).

example:

And its done.

Now when you start the Angular project. here we need to use

npm run start:dev

No need to use ng serve.

Note: You can modify the package.json script as you want…

Technical Support or Questions

If you have questions or need help integrating the editor please contact me at golapyd@gmail.com instead of opening an issue.

Buy me a coffee

--

--

Golap Hazarika

Senior Front-end Engineer and SSO Specialist at Vantage Circle