
[英]How to add new headers to the http request in angularjs through interceptors?
[英]Angularjs + interceptors + add query parameters for only http request( not html,js,css files)
我正在使用 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');
我使用此代码。 它运行良好,但我在开发工具(网络)中看到 html、css、js 文件也添加了参数。 喜欢。
http://localhost/webapp/views/template/left-menu.html?access_token=xxxxxxxxxxxxxxxxx
http://localhost/webapp/css/index.css?access_token=xxxxxxxxxxxxxxxxx
但我不喜欢将 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.
我希望只有后端 api 请求。 此外,我不希望每个服务 http 请求都添加参数。
可以在 config 中添加通用的一个地方吗?
您可以检查网址:
$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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.