简体   繁体   中英

Add a custom header in http get request angularjs.

This is my angularjs request.

var req = {
                method: 'GET',
                url: 'http://localhost:8080/test',
                headers: {
                    "x-auth-token" : user.token
                }
            }

            $http(req).success(function(){
                console.log("yes you have done it");
            }).error(function(){
                console.log("oopsss");
            });

I got this exception when I call this request.

XMLHttpRequest cannot load http://localhost:8080/test . Invalid HTTP status code 403

However in postman test of google chrome it works well and return me the response as I expect. I get this as.

The request header in postman test

GET /appraisal HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: no-cache
x-auth-token: 123456
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

And in the response header.

Access-Control-Allow-Origin:*
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Fri, 27 Mar 2015 16:13:46 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

But when I call my get request the brower shows http request header like this.

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:accept, x-auth-token
Access-Control-Request-Method:GET
Connection:keep-alive
Host:52.11.111.128:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/james/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36

And http response header is

Access-Control-Allow-Headers:x-auth-token
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Fri, 27 Mar 2015 17:03:16 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

I have enable cross request origin policy in my server.

How to request the header correctly ?

how to resolve this issue in my controller.

Please guide me towards this.

Thanks in advance.

We use a service for that which set the header for all requests against the REST-API. The service set the authorization header and looks like this:

app.factory('api', function($http) {
    function init(token) {
        $http.defaults.headers.common.Authorization = token || 'Basic xyztoken==';
    }
    return {
        init : init
    };
});

On our app.run we initialize the header:

app.run(function(api, …) {
    …
    api.init();
    …
});

And on our AuthService we set the authorization header with a new token:

app.factory('AuthService', function(api, …) {
    …
    // some login action with a response from the REST-API and 
    // set the new authorization header
    api.init('Bearer ' + response.data.accessToken);
    // some more stuff
    …
});

And in our controller you don't need to use custom header furthermore.

It only works if you use credentials . So you must set the withCredential flag on the config phase of your app:

app.config(function($httpProvider, …) {
    …
    $httpProvider.defaults.withCredentials = true;
    …
});

Ciao Ralf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM