Lahiru idangoda
Lahiru idangoda

Reputation: 45

How to solve "CORS policy: Response to preflight request doesn't pass access control check." without adding browser plugin

I know this question is very frequently asked and 100% duplicate of other questions. I tried the solutions defined in them, but they didn't work for me.So please kindly lookat my question and help me out here.

I am trying to call a GET method at the url https://www.webwork-tracker.com/rest-api/reports/full-data?start_date=2020-06-22&end_date=2020-06-22 from my local which is on http://localhost:4500 . I have defined proxy.confs.json and included the following lines in it,

"/rest-api" : {
"target" : "https://www.webwork-tracker.com",
"secure" : false
}

I call the url through this:

const username = '[email protected]';
const password = 'userPassword';
const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password)});
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return this.http.get<any>('https://www.webwork-tracker.com/rest-api/reports/' +
  'full-data?start_date=2020-06-22&end_date=2020-06-22', {headers});

I want to solve this without adding any browser plugins and I doesn't have the access to the backend server. So, the solution I found was adding proxy. But I still get the following error

Access to XMLHttpRequest at 'https://www.webwork-tracker.com/rest-api/reports/full-data?start_date=2020-06-22&end_date=2020-06-22' from origin 'http://localhost:4500' 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.

The API call works fine in the POSTMAN. And I understand the browser checks for the same origin before sending the get request as well. So the proxy helps me solve it. Can someone please help me to solve this?

Upvotes: 0

Views: 2586

Answers (1)

David
David

Reputation: 34425

In your service, you need to call a relative url, which will then be proxied

return this.http.get<any>('/rest-api/reports/' + ...)

Also since you are accessing a server not on localhost, you need to set changeOrigin (see the documentation)

"/rest-api" : {
"target" : "https://www.webwork-tracker.com",
 ...
 changeOrigin: true
}

Other points:

Make sure the proxy file proxy.conf.json matches the name in your angular.json (confs vs conf)

Also, HttpHeaders are immutable so your headers.append calls will have no effect (but you don't need them anyway)

const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(username + ':' + password)});
headers.append('Content-Type', 'application/json'); //no effect
headers.append('Accept', 'application/json');

Upvotes: 1

Related Questions