angular js在每个http请求$http上添加请求参数
angular js add request parameter on every http request $http
我想使用angular$http来与api交互,但我需要将我的auth令牌存储到$http,这样在每次请求中,无论帖子被放入删除,我都希望令牌存在,我也见过有人在标题中放置令牌,我知道如何将其放置在标题中,但我不确定将令牌放置在标题是否是一种好的做法,以下是我的配置:
config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $http) {
$urlRouterProvider.otherwise("/view1");
}]);
要与需要令牌身份验证的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、cookie或任何东西。
config$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';
}
根据HTTP规范,授权令牌的正确位置显然在标头中。
相关文章:
- Meteor如何接收HTTP请求
- 在我的情况下,如何进行http请求
- 使用插件收听Firefox标签的http请求
- Angularjs http.get() Cross-Origin 请求被阻止
- http请求使用html而不是json进行响应
- 在node-js路由中发出http请求
- 通过sdk/system/events在修改请求观测器上测试http
- 是否可以在没有HTTP请求或<输入>
- Acync JS HTTP请求通知请求
- PhantomJs在控制台中发出http请求时不会返回任何状态
- 当我在chrome中切换设备模式时,$http.get请求失败
- PHP处理来自一个页面的http请求,并将其显示在另一个页面上
- 使用angular js通过代理服务器请求Http
- 如何从HTTPS服务器请求HTTP服务器的javascript文件
- 阻止的跨来源请求:http://api.fixer.io/latest.
- 坏的请求.HTTP POST到api
- 有没有办法为AngularJS JSON请求($http/$resource)使用浏览器缓存?
- angular js在每个http请求$http上添加请求参数
- 当从不存在的站点请求HTTP响应时,Node.js脚本会中断
- 通过代理服务器请求HTTP呼叫