授权头在AJAX CORS请求中仅附加一次 [英] Authorization Header appended only once in AJAX CORS request
问题描述
我在CORS场景中从Javascript中调用我的RESTful API。
I'm calling my RESTful API from Javascript in a CORS scenario.
我使用JQuery发送POST验证请求。
这里是一个例子:
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);
}
在服务器端,我可以看到第一个调用来自'Authorization'
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.
我缺少什么?
谢谢
cghersi
推荐答案
我解决了我的问题给每个人的答案是在同样的情况下。
I solved my issue so I want to give the answer to everybody else is in the same situation.
1)问题是启用从服务器端的OPTIONS http请求。事实上,有一个第一次调用相同的url,但动词'OPTIONS',然后第二次调用到真实的url与POST | GET方法。如果服务器没有正确回答第一个OPTIONS调用,例如指定正确的允许标题等,第二个调用不起作用。
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)符号
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
这篇关于授权头在AJAX CORS请求中仅附加一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!