jquery - CORS 请求 - 为什么没有发送 cookie?

标签 jquery html 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
            }
        });

响应 header 包含一个 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 相关 header 是:

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
        });

关于jquery - CORS 请求 - 为什么没有发送 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8863571/

相关文章:

jquery - 根据内容使用 jquery 隐藏 td

javascript - 悬停时在相对标签内滚动绝对图像

javascript - 如何在 javascript/jquery 中分割字符串并测试字符串的开头?

javascript - 为什么在调用有效函数时会出现类型错误? | Angular 2

html - 轮廓和边框在 IE 中根本不显示

php - $_FILES 和 $_POST 使用 ajax

html - CSS HTML 对齐 div

javascript - Chrome 随机滚动 Javascript 事件

javascript - 如何只调试一个js文件

css - 使用相同浏览器(chrome)在不同机器上显示不同的页面