从 AJAX POST 响应中获取和存储 cookie(来自 Set-Cookie)



我有一个简单的jQuery AJAX POST代码:

$.ajax({
    type: "POST",
    url: AppConstants.URLs.PROXY,
    data: message,
    xhrFields: {
        withCredentials: true
    },
    success: function(data, status, xhr) {
        console.log("Cookie: " + xhr.getResponseHeader("Set-Cookie"));
    }
});

我希望获得cookie并使用cookie-js保存它。

但根据 http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method:

  1. 将所有响应标头(不包括与 Set-Cookie 或 Set-Cookie2 不区分大小写的标头)作为单个字符串返回,每个标头行由 U+000D CR U+000A LF 对分隔,不包括状态行,每个标头名称和标头值由 U+003A 冒号 U+0020 空格对分隔。

使用 Chrome 中的网络工具,"设置-Cookie"会显示在"响应"标头中。我还验证了"Set-Cookie"标头是否使用 curl 出现。

我该怎么做才能将 Cookie 保存在我的前端应用程序中?此外,我的应用程序仅在https上运行。

我很乐意根据要求提供更多详细信息。

您无法在 JS 中获取 cookie 数据。API 不允许你这样做。

我该怎么做才能将 Cookie 保存在我的前端应用程序中?

只需在服务器端代码的响应中设置 Set-Cookie 标头即可。浏览器应自动保存它。

作为开发者,您可以使用"开发者工具"检查 Cookie 的价值。

并且相同的 cookie 将在后续请求中发送到同一域,直到 cookie 过期。

出于安全原因,浏览器无法访问第三方cookie,例如从ajax请求中收到的cookie,但是它会自动为您处理这些cookie!

为此,您需要:

1) 使用您希望从中返回 cookie 的 AJAX 请求登录:

$.ajax("https://example.com/v2/login", {
     method: 'POST',
     data: {login_id: user, password: password},
     crossDomain: true,
     success: login_success,
     error: login_error
  });

2) 在下一个 ajax 请求中与xhrFields: { withCredentials: true }连接,以使用浏览器保存的凭据

$.ajax("https://example.com/v2/whatever", {
     method: 'GET',
     xhrFields: { withCredentials: true },
     crossDomain: true,
     success: whatever_success,
     error: whatever_error
  });

浏览器会为您处理这些 cookie,即使它们无法从headersdocument.cookie

读取

在这里查看我的答案:如何从 AJAX 响应中获取 cookie?

最新更新