CORS请求 – 为什么cookies没有发送?
我有一个跨域AJAX GET获得预先成功,但cookies不附加到GET请求。 当用户点击一个loginbutton时,一个POST被logging下来,这个用户可以跨域正确的工作。 JavaScript是:
$.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:
Set-Cookie:user_token=snippysnipsnip; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT
如果login成功,将获取JavaScript GET请求以获取当前用户的详细信息:
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相关头文件是:
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。
这个问题是与jQuery调用 – 似乎自1.5 withCredentials应指定为:
$.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 });