在AngularJS中添加HTTP标头不起作用

时间:2017-01-16 15:08:18

标签: javascript angularjs http angular-http-interceptors

我是AngularJS的新手,我试图将http标头添加到所有请求,但它无法正常工作。我实际上是尝试通过Angular中的.config添加它们

我的代码是:

 angular.module('sc.app',[])
    .provider('TokenHandler',['$q',function ($q) {
        return {
            $get: function () {
                return {
                    request: function (config) {
                        var defer = $q.defer();
                        console.log('jwt');
                        config.defaults.headers.common['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
                        config.defaults.headers.common['Accept'] = 'application/json;odata=verbose';

                        return defer.resolve(config);
                    },
                    requestError: function (err) {
                        var defer = $q.defer();
                        return defer.reject(err);
                    },
                    response: function (success) {                            
                   var defer = $q.defer();
                    console.log(success)
                    return defer.resolve(success);
                },
                responseError: function (err) {
                    var defer = $q.defer();
                    return defer.reject(err);
                }
            };
        }
    }
}])

.config(['$httpProvider','TokenHandler',function ($httpProvider,TokenHandler) {
    $httpProvider.interceptors.push('TokenHandler');
}])

.service('TokenService',['$http','$localStorage',function ($scope,$localStorage) {
    $scope.getToken=function () {
        return $localStorage.gaid;
    }

    $scope.setToken=function (token) {
        $localStorage.gaid=token;
    }
}]);

我google了很多但我无法解决它的问题。虽然我也试图添加config.headers选项但也没有工作。

我的请求标题是

GET /api/datatable.json?_=1484584475255 HTTP/1.1
Host: scrm.app
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
Referer: http://scrm.app/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,ta;q=0.6
Cookie: _ga=GA1.2.550730185.1483706923; 
XSRF-TOKEN=eyJpdiI6Ik9RaDBLeWluTVBIS0ZnOWkyaWxDUXc9PSIsInZhbHVlIjoiWlMzZUxONGthTmRKbkxxQjkxMGZWTE40d1lFYnAxRkRCM254b21abUpiOVFkd3VqbXowTjhlenFYa0xSazV1WmJuK2wweUFNZjVvM05NTXU3NjAwVmc9PSIsIm1hYyI6Ijg1Yzk0OWM3MTFkNTdlYTA1NjgzYjYyMmY3NmE1MWI0OTA4Mjc1MjM1ZTdkYTUxOWUxZmZhYjFlNzRmNzc2MDkifQ%3D%3D; laravel_session=eyJpdiI6InZqb01UbDRNVFgrTG1FVitvZW1WQXc9PSIsInZhbHVlIjoic3NKUXo5ZGd5ODBpZXhNRXBsa1pmbVhFSmhUVDA3RkZyQ3FcL1VlOVRZUWt4UlVxZVlidlU4VUV5VjBCZFwvUldCbzZVNU83R25zMXpRZ25DTENTZGpsUT09IiwibWFjIjoiZjNjNWM2OWU2ZDM3NDVlNDRkYTRhMjk4MmM4NWJmNjI0ODQyMmQwMjkzZTBkZWQ3N2ZjZTg4YzdjYTljZWNjNCJ9

我的回复标题

 HTTP/1.0 404 Not Found
Host: scrm.app
Connection: close
X-Powered-By: PHP/5.6.27
Cache-Control: no-cache, private
Date: Mon, 16 Jan 2017 16:49:42 GMT
Content-type: text/html; charset=UTF-8

1 个答案:

答案 0 :(得分:0)

通过配置添加标头时,您只需要config.headers,例如 -

config.headers['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
config.headers['Accept'] = 'application/json;odata=verbose';

只有在通过$http服务添加时才需要其他服务,例如 -

 $http.defaults.headers.common.Authorization = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';

编辑:另一种尝试将以下内容添加到.service块 -

的方法
.service('TokenService',['$http','$localStorage',function ($scope,$localStorage) {  
     var service = this;

    service.request = function(config) {
        config.headers['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
        config.headers['Accept'] = 'application/json;odata=verbose';

        return config;
    };
......