Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

I am trying to send the request from one localhost port to the another. I am using angularjs on the frontend and node on the backend.

Since it is CORS request, In node.js, i am using

res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); 

and in the angular.js service file, I am using

return {     getValues: $resource(endpoint + '/admin/getvalues', null, {         'get': {              method: 'GET',              headers:{'Authorization':'Bearer'+' '+ $localStorage.token}              }      }), } 

I am getting the following error

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Please help!

like image 261
Abhishek Kulshrestha Avatar asked Feb 06 '17 06:02

Abhishek Kulshrestha


People also ask

What is CORS policy no Access-Control allow origin?

To allow any site to make CORS requests without using the * wildcard (for example, to enable credentials), your server must read the value of the request's Origin header and use that value to set Access-Control-Allow-Origin , and must also set a Vary: Origin header to indicate that some headers are being set ...


1 Answers

You have to add options also in allowed headers. browser sends a preflight request before original request is sent. See below

 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS'); 

From source https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

In CORS, a preflight request with the OPTIONS method is sent, so that the server can respond whether it is acceptable to send the request with these parameters. The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the server that when the actual request is sent, it will be sent with a X-PINGOTHER and Content-Type custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.

EDITED

You can avoid this manual configuration by using npmjs.com/package/cors npm package.I have used this method also, it is clear and easy.

like image 99
vikas Avatar answered Sep 22 '22 21:09

vikas