【问题标题】:angular js add request parameter on every http request $httpangular js在每个http请求$http上添加请求参数
【发布时间】:2017-01-06 18:23:54
【问题描述】:

我想使用 Angular $http 与 api 交互,但我需要将我的身份验证令牌存储到 $http 以便在每个请求中发布删除,我希望令牌存在,我也有看到人们将标记放在标题中,我知道如何将其放置在标题中,但我不确定将标记放在标题中是否是一个好习惯,这是我的配置:

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

}]);

【问题讨论】:

  • 如果有帮助,请尝试使用Restangular,这是一个很棒的库!您可以一次性配置 Rectangular,然后在所有调用中都拥有令牌
  • 你在你的配置中注入了 $http 吗?那应该是不可能的。

标签: javascript angularjs


【解决方案1】:

要与需要令牌认证的 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、cookies 或任何东西。

【讨论】:

    【解决方案2】:

    在启动时配置 $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';
    }
    

    【讨论】:

      【解决方案3】:

      清楚地遵循 HTTP 规范,授权令牌的正确位置是在标头中。

      【讨论】:

      • 如果@Mikail 需要执行一些逻辑才能在他的 ajax 调用的标头中使用令牌,那么在这里使用拦截器不是更好吗?
      • 授权token可以通过多种方式添加到header中,具体根据需要和要求来决定。你说得对,使用拦截器可能会更好。我已经编辑了我的答案,谢谢
      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 2015-12-31
      • 2016-11-03
      • 2016-08-11
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      相关资源
      最近更新 更多