how do I get round CORS in angular 9

Viewed 15677

I receive the following error:

Access to XMLHttpRequest at 'http://localhost:40000/api/summaryCount/failed-requests' from origin
'http://localhost:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have created a proxy.conf.json file with the following:

{"/api/*": {
    "target": "http://localhost:40000",
    "secure": false
  }
}

I have also amended my angular.json file to include

"proxyConfig": "proxy.conf.json"

on the "serve": { "options" { ......

and finally I have amended my package.json so that the "start" option now becomes:

"start": "ng serve --proxy-config proxy.conf.json",

in my Angular when creating the HttpHeaders object, if I add the following:

httpHeaders = new HttpHeaders().append('Access-Control-Allow-Origin', 'http://localhost:3000').....

it still makes no difference.

can someone tell me what I've missed please.

2 Answers

You have to enable CORS and whitelist your Angular app URL http://localhost:3000 on your backend server which serves at http://localhost:40000/api/....

No action required on Angular app side.

In backend server, you have to write Access-Control-Allow-Origin as * and if you prevent from a specific URL then you can also write the URL there.

Related