Javascript angular js在每个http请求上添加请求参数$http

Javascript angular js在每个http请求上添加请求参数$http,javascript,angularjs,Javascript,Angularjs,我想使用angular$http与api进行交互,但我需要将我的身份验证令牌存储到$http,以便在每次请求中,无论是post get put delete,我都希望令牌存在,而且我也见过有人将令牌放在头中,我知道如何将其放在头中,但我不确定将令牌放在头中是否是一种好的做法,这是我的配置: config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $ht

我想使用angular$http与api进行交互,但我需要将我的身份验证令牌存储到$http,以便在每次请求中,无论是post get put delete,我都希望令牌存在,而且我也见过有人将令牌放在头中,我知道如何将其放在头中,但我不确定将令牌放在头中是否是一种好的做法,这是我的配置:

config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $http) {
  $urlRouterProvider.otherwise("/view1");

}]);

启动时配置$httpProvider

'use strict';

angular.module('app')
    .config(configHttp);

configHttp.$inject = ['$httpProvider'];
function configHttp($httpProvider) {
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }
    //disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    // extra
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get.Pragma = 'no-cache';
    // User Credential
    $httpProvider.defaults.headers.post['user-credential'] = 'xxxxxx';
}

按照HTTP规范,授权令牌的正确位置显然在头中。

要与需要令牌身份验证的API通信,需要设置拦截器

在配置文件中:

function config(..., $httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
    ...
}
angular
    .module('app')
    .config(config);
authInterceptor是一个工厂,负责向所有$http请求添加头:

function authInterceptor($rootScope, $q, $window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        responseError: function (rejection) {
            if (rejection.status === 401) {
                console.log("not authorised");
            }
            return $q.reject(rejection);
        }
    };
};

angular
    .module('app')
    .factory('authInterceptor', authInterceptor);

令牌可以来自会话存储、cookie或任何东西。

如果有帮助,请尝试使用
restanglar
这是一个了不起的库!您可以一次性配置矩形,并且在所有调用中都有您在配置中注入$http的令牌?这应该是不可能的。如果@Mikail在使用ajax调用头中的令牌之前需要执行一些逻辑,那么在这里使用拦截器不是更好吗?授权令牌可以以多种方式添加到头中,并且应该根据需要和要求来决定。你说得对,在这种情况下,最好使用拦截器。。我已经编辑了我的答案,谢谢