【问题标题】:How to add new headers to the http request in angularjs through interceptors?如何通过拦截器向angularjs中的http请求添加新的标头?
【发布时间】:2015-09-07 23:18:41
【问题描述】:
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);

            });
        }]);

我想为拦截器的请求添加新的标头。如何添加它?我已经尝试过上面的代码。谁能帮我解决这个问题?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    配置:

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

    服务:

    app.service('APIInterceptor', [function() {
        var service = this;
    
        service.request = function(config) {
            config.headers.YOUR_HEADER= YOUR_HEADERS_VALUE;
            return config;
        };
    }]);
    

    【讨论】:

    • 如果我使用这个,我会收到一个错误 Invalid left-hand side in assignment
    • module.service('APIInterceptor', [function() { var service = this; service.request = function(config) { config.headers.X-testing = 'testing'; return config; }; }]);
    • 尝试:config.headers['X-testing'] = 'testing';
    猜你喜欢
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2021-03-15
    • 2015-11-18
    • 2018-01-31
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多