Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular interceptors and CORS

I am trying to write an interceptor to add a token to all HTTP requests using Angular. I am using roughly the recipe given here - https://thinkster.io/interceptors

So the code uses http module factory and a tokenInterceptor() function. I can successfully add a token as a header to the request - but now when it passes through the interceptor, it gets blocked by some kind of CORS blocking mechanism. I get this error in chrome console -

XMLHttpRequest cannot load http://127.0.0.1:/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:/' is therefore not allowed access. The response had HTTP status code 403.

I tried setting the access control allow origin header like below in my interceptor to no avail:

config.headers['Access-Control-Allow-Origin'] = '*';

I have tried some suggestions online but none helped. Does anything at all need to be done on client side to fix CORS related issues - or is it all a server side concern?

like image 990
lenniekid Avatar asked May 10 '17 21:05

lenniekid


1 Answers

The server that’s responding to the request needs to send the Access-Control-Allow-Origin response header for OPTIONS requests, not just for GET and POST requests.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

Response to preflight request doesn't pass access control check

The reason the browser gives you that error is: before it attempts the actual request you’re trying to make from your frontend JS code, the browser sends an OPTIONS request to see if the server responds in a way indicating it’s opting in to receiving requests of the kind you’re trying to make.

So your server-side code needs to add handling for the OPTIONS request to respond with Access-Control-Allow-Origin, Access-Control-Allow-Headers & Access-Control-Allow-Methods.

Does anything at all need to be done on client side to fix CORS related issues - or is it all a server side concern?

There’s nothing you can do on the client side to change the behavior or to get your browser to not emit that error. CORS config is all a server-side concern. Your server must handle the OPTIONS.

The response had HTTP status code 403.

That indicates an authorization failure. That could be just because your server isn’t configured to ever send a success response (200 or 204) for OPTIONS requests—in which case you must configure to to do that (to send a 200 or 204 with the right Access-Control-Allow-* headers and no response body)—or it could be because you’re trying to send a request that requires authorization and the authorization is failing.

like image 130
2 revs Avatar answered Oct 19 '22 11:10

2 revs