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

angular js add request parameter on every http request $http

本文关键字:请求 http 添加 参数 js angular      更新时间:2023-09-26

我想使用angular$http来与api交互,但我需要将我的auth令牌存储到$http,这样在每次请求中,无论帖子被放入删除,我都希望令牌存在,我也见过有人在标题中放置令牌,我知道如何将其放置在标题中,但我不确定将令牌放置在标题是否是一种好的做法,以下是我的配置:

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

要与需要令牌身份验证的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);

令牌可以来自sessionStorage、cookie或任何东西。

config$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规范,授权令牌的正确位置显然在标头中。