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

2023-12-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 调用上 - 从 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
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CORS 请求 - 为什么未发送 cookie? 的相关文章

随机推荐