[英]angular js add request parameter on every http request $http
我想使用angular $ http與api進行交互,但是我需要將我的身份驗證令牌存儲到$ http,以便在每個請求中發送刪除,我希望令牌存在,我也看到人們放置標題中的標記,我知道如何將它放在標題中,但我不確定在標題中放置標記是否是一個好習慣,這是我的配置:
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';
}
要與需要令牌身份驗證的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或任何東西。
遵循HTTP規范,授權令牌的正確位置在標題中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.