【问题标题】:CORS request - why are the cookies not sent?CORS 请求 - 为什么不发送 cookie?
【发布时间】:2012-02-10 10:10:20
【问题描述】:

我有一个成功预飞行的跨域 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
            }
        });

响应标头包含一个 cookie:

Set-Cookie:user_token=snippysnipsnip; path=/; expires=Wed, 14-Jan-2032 16:16:49 GMT

如果登录成功,则发出 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 html google-chrome cors


    【解决方案1】:

    问题出在 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
            });
    

    【讨论】:

    • 花费了 4 小时来完成这项工作。希望我以前看过这篇文章。谢谢!
    • PUT/OPTIONS 的工作方式似乎不同。为什么 GET/POST 会发送 cookie 而不是 PUT 预检 OPTIONS 请求?
    • Cookie 在 localhost 上不起作用(未设置)。如果您需要在本地使用 cookie,请改用基于 ip 的域(例如127.0.0.1)。
    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 2021-05-29
    • 2021-07-05
    • 1970-01-01
    • 2018-11-16
    • 2015-02-11
    • 2015-08-29
    相关资源
    最近更新 更多