Authorization Header appended only once in AJAX CORS request

Deadly 提交于 2019-12-25 01:52:05

问题


I'm calling my RESTful API from Javascript in a CORS scenario.

I'm using JQuery to send my POST authenticated request. Here is an example:

function post(settings, addAccessToken) {
        settings.type = 'POST';
        settings.cache = false;
        if (settings.dataType === undefined)
            settings.dataType = 'json';
        if (addAccessToken) {
            settings.xhrFields = { withCredentials: true };
            settings.beforeSend = function (request) {
                request.setRequestHeader('Authorization', 'Bearer <my access token>');
            };
            settings.headers = {
                'Authorization': 'Bearer <my access token>'
            };
        }
        return $.ajax(settings);
    }

On server side, I can see the first call coming with the 'Authorization' Header correctly valued, while all the others don't have such Header.

What am I missing?

Thank you

cghersi


回答1:


I solved my issue so I want to give the answer to everybody else is in the same situation.

1) The problem was to enable OPTIONS http request from server-side. In fact, there is a first call to the same url but with verb 'OPTIONS' and then a second call to the real url with POST|GET method. If the server doesn't properly answer to the first 'OPTIONS' call, e.g. specifying the correct Allowed Headers etc., the second call doesn't work.

2) The notation

settings.headers = {
 'Authorization': 'Bearer <my access token>'
};

is not working. The only way to setup an header is:

settings.beforeSend = function (request) {
 request.setRequestHeader('Authorization', 'Bearer <my access token>');
};

Hope this can help other people in the future.

cghersi



来源:https://stackoverflow.com/questions/27990010/authorization-header-appended-only-once-in-ajax-cors-request

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