如何通过拦截器向angularjs中的http请求添加新的标头? [英] How to add new headers to the http request in angularjs through interceptors?

查看:32
本文介绍了如何通过拦截器向angularjs中的http请求添加新的标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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');
} ]);

服务:

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

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

这篇关于如何通过拦截器向angularjs中的http请求添加新的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆