RSK*_*KMR 3 factory http interceptor angularjs
我正在使用angularjs,在后端我检查每个api身份验证.每个请求都应该检查参数access_token.
$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
return {
request : function(config) {
config.params = config.params || {};
if ($localStorage.access_token) {
config.params.access_token = $localStorage.access_token;
}
return config || $q.when(config);
},
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor');
Run Code Online (Sandbox Code Playgroud)
我用这个代码.它工作得很好,但我在开发工具(网络)中看到html,css,js文件也添加了参数.喜欢.
http://localhost/webapp/views/template/left-menu.html?access_token=xxxxxxxxxxxxxxxxx
http://localhost/webapp/css/index.css?access_token=xxxxxxxxxxxxxxxxx
Run Code Online (Sandbox Code Playgroud)
但我不喜欢将access_token发送到所有http请求(html,css,js).
我喜欢发送带有前缀api的access_token
http://localhost:9090/api/user/get?access_token=xxxxxxxxxxxxxxxxxxxxxx
//I think the solution is find the http url and grep the text api, if found means add the parameter. Don't konw this is good approach.
Please me the good approach.
Run Code Online (Sandbox Code Playgroud)
我只期望只有后端api请求.另外,我不希望每个严格的http请求添加参数.
可以在config中添加常见的一个位置吗?
小智 7
你可以检查网址:
$provide.factory('MyHttpInterceptor', function($q, $location, $localStorage) {
return {
request : function(config) {
var apiPattern = /\/api\//;
config.params = config.params || {};
if ($localStorage.access_token && apiPattern.test(config.url)) {
config.params.access_token = $localStorage.access_token;
}
return config || $q.when(config);
}
};
});
// Add the interceptor to the $httpProvider.
$httpProvider.interceptors.push('MyHttpInterceptor');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4529 次 |
最近记录: |