AngularJS: $http interceptor change every call method to OPTIONS

两盒软妹~` 提交于 2019-12-20 02:57:24

问题


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');
}

回答1:


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.



来源:https://stackoverflow.com/questions/27800129/angularjs-http-interceptor-change-every-call-method-to-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!