AngularJS如何在每个HTTP请求中添加请求参数:$http

3
我想使用angular $http与api进行交互,但我需要将我的认证令牌存储到$http中,以便在每个请求中无论是post、get、put还是delete,我都希望令牌存在。我知道有些人将令牌放置在标头中,我知道如何将其放置在标头中,但我不确定将令牌放置在标头中是否是一个好的实践方法。这是我的配置:
config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $http) {  $urlRouterProvider.otherwise("/view1");}]);

如果可以的话,尝试使用 Restangular 这个非常棒的库!你只需要在一次配置中设置好 Rectangular,然后在所有调用中都可以使用 token。 - gianlucatursi
你在配置文件中注入了 $http 吗?这不应该是可能的。 - gyc
3个回答

1

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

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或任何其他地方。

0
根据HTTP规范,授权令牌的正确位置显然是在头部。

在这里使用拦截器是否更好,以防@Mikail在使用其ajax调用标头中的令牌之前需要执行某些逻辑? - Chris
授权令牌可以通过多种方式添加到标头中,这应该根据需求和要求来决定。你说得对,也许最好使用拦截器...我已经编辑了我的答案,谢谢。 - Yosvel Quintero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接