是否可以从 JavaScript 的 HTTP 响应头中获取 Set-Cookie 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7197455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to get the Set-Cookie value from an HTTP response header in JavaScript?
提问by Dan Tao
I'm using jQuery's ajax()
methodto make some asynchronous server calls and want to catch the case where a call fails because the session has timed out.
我正在使用jQuery 的ajax()
方法进行一些异步服务器调用,并希望捕获由于会话超时而导致调用失败的情况。
From looking at the response headers in this case, I see that they include
在这种情况下,通过查看响应标头,我看到它们包括
Set-Cookie: SMSESSION=LOGGEDOFF
which seems like a pretty reliable test. But calling getAllResponseHeaders
on the XMLHttpRequest
object passed to jQuery's error
callback apparently returns an empty string, and I'm having trouble figuring out any other way of getting that header information.
这似乎是一个非常可靠的测试。但是调用传递给 jQuery回调getAllResponseHeaders
的XMLHttpRequest
对象error
显然会返回一个空字符串,而且我无法找出获取该标头信息的任何其他方法。
Is this possible?
这可能吗?
回答by Andre
If you read the W3 XHR spec you'll see that they don't allow you to access the set-cookie
response header via a getAllResponseHeaders('Set-Cookie')
call.
如果您阅读 W3 XHR 规范,您会发现它们不允许您set-cookie
通过getAllResponseHeaders('Set-Cookie')
调用访问响应标头。
See 4.7.3 The getResponseHeader() method:
见 4.7.3 getResponseHeader() 方法:
Bullet point 3: "If header is a case-insensitive match for Set-Cookie or Set-Cookie2, return null."
要点 3:“如果标头是 Set-Cookie 或 Set-Cookie2 的不区分大小写匹配,则返回 null。”
http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method
http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method
jfriend00 also left this response in the comments above but I thought this question could use a legitimate answer.
jfriend00 也在上面的评论中留下了这个回应,但我认为这个问题可以使用合法的答案。
回答by Jon Cooke
If the document is from the same domain and path, use the document.cookie interface If the cookie has the http-only attribute set, it's inaccessible
如果文档来自相同的域和路径,则使用 document.cookie 接口 如果 cookie 设置了 http-only 属性,则无法访问