CORS请求 - 为什么不发送cookie?

jim*_*_vx 54 html jquery google-chrome cors

我有一个跨域AJAX GET成功预先通过,但cookie没有附加到GET请求.当用户单击登录按钮时,将进行POST以将用户登录,这可以跨域正常工作.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
            }
        });
Run Code Online (Sandbox Code Playgroud)

响应标头包含一个cookie:

Set-Cookie:user_token=snippysnipsnip; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT
Run Code Online (Sandbox Code Playgroud)

如果登录成功,则会发出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;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

从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
Run Code Online (Sandbox Code Playgroud)

但是,GET请求中不会发送任何cookie.

jim*_*_vx 76

问题出在于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
        });
Run Code Online (Sandbox Code Playgroud)

  • 花了4个小时让它工作.希望我以前见过这篇文章.谢谢! (7认同)
  • Cookie在localhost上无法正常工作(未设置).如果您需要在本地使用cookie,请使用基于ip的域(例如`127.0.0.1`). (2认同)