身份验证信息的目的,是为了向服务器表明身份,获取数据。所以,在请求中需要附加身份验证信息。
一般的应用中,身份验证信息都是放在请求的 headers 头部中
Angular 中的 $httpProvider 提供了一个拦截器 interceptors ,通过它可以实现对每一个请求和响应的统一处理。
示例:给所有请求头配置Authorization
(function() {
'use strict';
angular
.module('ejt1GatewayApp')
.factory('authInterceptor', authInterceptor);
authInterceptor.$inject = ['$rootScope', '$q', '$location', '$localStorage', '$sessionStorage'];
function authInterceptor ($rootScope, $q, $location, $localStorage, $sessionStorage) {
var service = {
request: request
};
return service;
function request (config) {
config.headers = config.headers || {};
config.headers["Accept-Language"] =$localStorage.selectLanguage;
var token = $localStorage.authenticationToken || $sessionStorage.authenticationToken;
// var lang='Accept-Language';
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
}
}
})();
// 使用拦截器
http.config.js
(function() {
'use strict';
angular
.module('ejt1GatewayApp')
.config(httpConfig);
httpConfig.$inject = ['$urlRouterProvider', '$httpProvider', 'httpRequestInterceptorCacheBusterProvider', '$urlMatcherFactoryProvider'];
function httpConfig($urlRouterProvider, $httpProvider, httpRequestInterceptorCacheBusterProvider, $urlMatcherFactoryProvider) {
//$httpProvider.interceptors.push('logResponseInterceptor');
}
})();