CORS request - why are the cookies not sent?(CORS 请求 - 为什么不发送 cookie?)
问题描述
我有一个成功预飞行的跨域 AJAX GET,但 cookie 没有附加到 GET 请求.当用户单击登录按钮时,会进行 POST 以使用户登录,这可以跨域正常工作.JavaScript 是:
I have a cross-domain AJAX GET which gets pre-flighted successfully, but the cookies don't get attached to the GET request. When the user clicks a log in button, a POST is made to log the user in, which works correctly cross domain. The JavaScript is:
$.ajax(signin_url, {
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(credentials),
success: function(data, status, xhr) {
signInSuccess();
},
error: function(xhr, status, error) {
signInFailure();
},
beforeSend: function(xhr) {
xhr.withCredentials = true
}
});
响应标头包含一个 cookie:
The response headers include a cookie:
Set-Cookie:user_token=snippysnipsnip; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT
如果登录成功,则发出 JavaScript GET 请求以获取当前用户的详细信息:
If sign-in succeeds, a JavaScript GET request is made to get the current user's details:
function signInSuccess() {
$.ajax(current_user_url, {
type: "GET",
contentType: "application/json; charset=utf-8",
success: function(data, status, xhr) {
displayWelcomeMessage();
},
beforeSend: function(xhr) {
xhr.withCredentials = true;
}
});
}
Chrome 的 OPTIONS 请求返回的与 CORS 相关的标头是:
The CORS-related headers returned from Chrome's OPTIONS request are:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With, X-Prototype-Version, Content-Type, Origin, Allow
Access-Control-Allow-Methods:POST, GET, OPTIONS
Access-Control-Allow-Origin:http://192.168.0.5
Access-Control-Max-Age:1728000
但是,GET 请求不会发送任何 cookie.
However, no cookies are sent on the GET request.
推荐答案
问题出在 jQuery 调用上 - 从 1.5 开始似乎应该将 withCredentials 指定为:
The issue was with the jQuery calls - it seems since 1.5 withCredentials should be specified as:
$.ajax("http://localhost:3000/users/current", {
type: "GET",
contentType: "application/json; charset=utf-8",
success: function(data, status, xhr) {
hideAllContent();
$("#sign_out_menu_item").show();
$("#sign_in_menu_item").hide();
$("#welcome").text("Welcome " + data["username"] + "!");
$("#welcome").show();
},
xhrFields: {
withCredentials: true
},
crossDomain: true
});
这篇关于CORS 请求 - 为什么不发送 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:CORS 请求 - 为什么不发送 cookie?
基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01