AngularJS:$ HTTP拦截改变每次调用方法OPTIONS [英] AngularJS: $http interceptor change every call method to OPTIONS
问题描述
所以,我试图拦截HTTP调用是否存在添加在每个呼叫的Authorization头。
这种运作良好exept的事实,不管我使用的HTTP方法(GET,POST,DELETE)发送与OPTIONS方法请求来代替。我究竟做错了什么?
服务器是用的NodeJS的RESTify。
angular.module('mymodule中')。工厂('RequestService',函数(){
VAR令牌= NULL; VAR的服务= {
setToken:功能setToken(_token){
令牌= _token;
}, 为gettoken:功能为gettoken(){
返回记号。
}, 要求:功能要求(配置){
如果(标记){
config.headers ['授权'] ='令牌'+令牌;
}
返回配置;
} } 退换货服务;
})。配置(函数($ httpProvider){
$ httpProvider.interceptors.push('RequestService');
}
当您实现在前端侧自己的拦截器,你应该记住CORS:
app.use(功能(REQ,资源,下一个){
res.header('访问控制允许来源,req.headers.origin ||*);
res.header(访问控制允许的方法,GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header(访问控制允许报头,内容类型,X要求 - 带,authorization123456,接受');
下一个();
});
我们要记得设置方法,以及对头艾策斯 - 控制研究 - 允许。在我的情况下,它的'authorization123456在这里我把我的令牌将被添加到从AngularJS每个请求。
So, I'm trying to intercept the http calls to add the Authorization header on each call if exist. This works well exept of the fact that no matter which http method I use (GET, POST, DELETE) it send the request with OPTIONS method instead. What am I doing wrong?
Server is nodejs with restify.
angular.module('mymodule').factory('RequestService', function () {
var token = null;
var service = {
setToken: function setToken(_token) {
token = _token;
},
getToken: function getToken() {
return token;
},
request: function request(config) {
if (token) {
config.headers['Authorization'] = 'Token' + token;
}
return config;
}
}
return service;
}).config(function($httpProvider) {
$httpProvider.interceptors.push('RequestService');
}
When you implement your own interceptor on Front-End side, you should remember about CORS:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || "*");
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-Type,x-requested-with,authorization123456,accept');
next();
});
We should remember to set Acces-Controll-Allow on Methods as well as on Headers. In my case it's 'authorization123456' where I put my token which is added to every request from AngularJS.
这篇关于AngularJS:$ HTTP拦截改变每次调用方法OPTIONS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!