Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to XMLHttpRequest has been blocked by CORS policy

I've a problem when I try to do PATCH request in an angular 7 web application. In my backend I have:

app.use((req, res, next) => {     res.set({         "Access-Control-Allow-Origin": "*",         "Access-Control-Allow-Methods": "*",         "Access-Control-Allow-Headers": "'Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'",     });      next(); }); 

In my frontend service, I've:

  patchEntity(ent: any, id) {     let headers = new Headers({ 'Content-Type': '*' });     let options = new RequestOptions({ headers: headers });     return this.http.patch('my_url', ent).map((res: Response) => res.json());   }; 

The error is:

Access to XMLHttpRequest at 'my_url' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. 

What can I to do? Thanks.

like image 734
rikg93 Avatar asked Nov 12 '18 08:11

rikg93


People also ask

How do I fix a blocked CORS policy?

Use a Chrome extension to add Access-Control-Allow-Origin header into every response. To find one of them, just head over to Chrome Webstore and type in "CORS", dozens will show up in the search result. Or you can install CORS Helper, CORS Unblock or dyna CORS right away.

How do I resolve access to XMLHttpRequest?

In simple words, this error occurs when we try to access a domain/resource from another domain. To fix this, if you have access to the other domain, you will have to allow Access-Control-Allow-Origin in the server. This can be added in the headers. You can enable this for all the requests/domains or a specific domain.


1 Answers

There are two ways this can be handled:

  1. Temporary Front-End solution so you can test if your API integration is working:

Click on window -> type run and hit enter -> in the command window copy:

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

This will open a new "Chrome" window where you can work easily. This is a temporary solution. Every time you will have to work with this chrome window.

  1. Permanent solution:

In the backend code, the developer needs to add an annotation @Crossorigin right above the CRUD api call method.

Let me know if it works.

like image 70
Bitly Avatar answered Oct 10 '22 01:10

Bitly