简体   繁体   English

如何通过拦截器向angularjs中的http请求添加新标头?

[英]How to add new headers to the http request in angularjs through interceptors?

var module = angular.module('timestamp-marker-example', []);
        module.factory('timestampMarker',[function() {
            var timestampMarker = {
                request: function(config) {
                    console.log(config);
                    console.log(config.method);
                    console.log(config.url);
                   /* console.log(config.headers);*/
                    var head={
                            headers:{
                                'X-testing':'testing'
                            },
                            method:"POST"
                    }
                    config.push(head);      



                    return config ;
                },
                response: function(response) {

                   return response;
                }
            };
            return timestampMarker;
        }]);
        module.config(['$httpProvider', function($httpProvider) {
            $httpProvider.interceptors.push('timestampMarker'); 
        }]);

        module.controller('ExampleController', ['$scope', '$http', function($scope, $http) {

            $http.get('https://api.github.com/users/naorye/repos').then(function(response) {
                console.log(response);

            });
        }]);

I want to add new headers to the request from the interceptors. 我想从拦截器向请求添加新标头。 How to add it? 如何添加? I have tried in the above code. 我试过上面的代码。 Can anyone help me solve this problem? 任何人都可以帮我解决这个问题吗?

Config : 配置:

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

Service : 服务:

app.service('APIInterceptor', [function() {
    var service = this;

    service.request = function(config) {
        config.headers.YOUR_HEADER= YOUR_HEADERS_VALUE;
        return config;
    };
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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