从 AJAX POST 响应中获取和存储 cookie(来自 Set-Cookie) [英] Get and store cookie (from Set-Cookie) from an AJAX POST response

查看:99
本文介绍了从 AJAX POST 响应中获取和存储 cookie(来自 Set-Cookie)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$.ajax({类型:POST",网址:AppConstants.URLs.PROXY,数据:消息,xhr 字段:{withCredentials: 真},成功:功能(数据,状态,xhr){console.log("Cookie:" + xhr.getResponseHeader("Set-Cookie"));}});

我希望获取 cookie 并使用 cookies-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 COLON U+0020 空格对分隔.

使用 Chrome 中的网络工具,Set-Cookie"在响应标头中可见.我还使用 curl 验证了Set-Cookie"标头出现.

我需要做什么才能在我的前端应用程序中保存 cookie?此外,我的应用仅在 https 上运行.

我很乐意应要求提供更多详细信息.

解决方案

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

<块引用>

我需要做什么才能在我的前端应用中保存 cookie?

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

作为开发人员,您可以使用开发人员工具"检查 cookie 的价值.

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

I have a simple jQuery AJAX POST code:

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

and I wish to get the cookie and save it using cookies-js.

But according to http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method:

  1. Return all response headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.

Using the Network tool in Chrome, "Set-Cookie" is visible in the Response headers. I also verified that the "Set-Cookie" header appears using curl.

What do I have to do to save the cookie in my front end app? Also, my app is running on https only.

I'd gladly provide more details upon request.

解决方案

You can't get the cookie data in your JS. The API won't allow you.

What do I have to do to save the cookie in my front end app?

Just set the Set-Cookie header in the response from the server side code. The browser should save it automatically.

As a developer, you may be able to inspect the value of the cookies using "Developer Tools".

And the same cookie will be sent in subsequent requests to the same domain, until the cookie expires.

这篇关于从 AJAX POST 响应中获取和存储 cookie(来自 Set-Cookie)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆