angular js在每个http请求$ http上添加请求参数 [英] angular js add request parameter on every http request $http
问题描述
我想使用angular $ http与api进行交互,但是我需要将我的身份验证令牌存储到$ http,以便在每个请求中发送删除,我希望令牌存在,我也有看到人们在标题中放置令牌,我知道如何将它放在标题中,但我不确定将标记放入标题是否是一个好习惯,这是我的配置:
I'd like to use angular $http to interact with api, but I need to store my auth token to $http so that in every request wether post get put delete, I want the token to be present, also I have seen people place tokens in the header , I know how to place it in the header, but I'm not sure if its a good practice to put tokens in the header , here is my config :
config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $http) {
$urlRouterProvider.otherwise("/view1");
}]);
推荐答案
要与需要令牌身份验证的API进行通信,需要设置一个拦截器。
To communicate with an API that requires token authentification, you need to set up an interceptor.
在你的配置文件中:
function config(..., $httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
...
}
angular
.module('app')
.config(config);
authInterceptor是一个工厂,负责为所有$ http请求添加标头:
authInterceptor is a factory that will take care of adding headers to all your $http requests:
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或任何东西。
The token can come from sessionStorage, cookies or anything.
这篇关于angular js在每个http请求$ http上添加请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!