Angularjs set authorization header

I am trying to put the authorization header in my requests, but it does not work.

I use this:

var config = {headers: { 'Authorization': token } }; return $http.get('http://localhost:3000/apis/users/all', config); 

And also I tried this:

 $http.defaults.headers.common['Authorization'] = token; 

But in both cases, I got the headers in the return request:

 Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:es-ES,es;q=0.8,ca;q=0.6,en;q=0.4,gl;q=0.2 Access-Control-Request-Headers:accept, authorization Access-Control-Request-Method:GET Connection:keep-alive Host:localhost:3000 Origin:http://localhost:8000 Referer:http://localhost:8000/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 

I need something like this:

 Authorization: token 

But I got this:

 Access-Control-Request-Headers:accept, authorization 

Then I have no token value.

I use expressjs for the back-end, and I use this for CORS:

 app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); next(); }); 

Also say testing with Chrome Advance Rest Client is working fine. The request header contains authorization: valueOfToken ..

Thank you very much.

+6
source share
3 answers

Authorization cannot be simple.

indicate weather conditions: Basic or Bearer

Sort of

 $http.defaults.headers.common['Authorization'] = 'Basic ' + token; 

or

 $http.defaults.headers.common['Authorization'] = 'Bearer ' + token; 
+13
source

I had the same problem and it turned out that the problem was with Apache server-side configuration. One thing that I discovered may be useful for you is that my authorization token is sent in the preflight request headers and not in the main request, so it may not appear in the request headers when you look at it in the developer tools.

I set my default settings as follows:

 app.config(function($httpProvider) { $httpProvider.defaults.common['Authorization'] = token; // For angular 1.5, use: // $httpProvider.defaults.headers.common['Authorization'] = token; }); 
+3
source

Try the following:

 $http({ url : "127.0.0.1/login", method : 'GET', headers : { Content-Type : 'application/json', Authorization: token } }).success(function(data){ alert("login Successfully"); }).error(function(error){ alert("login error"); }) 
+1
source

All Articles