什么可能导致不在客户端上设置Cookie? [英] What can cause a cookie not to be set on the client?
问题描述
我有一个web应用程序使用jQuery.ajax执行请求到另一个主机(现在实际上是相同的,因为我使用不同的端口localhost)。
Chrome的开发工具中显示的HTTP响应中的Cookie值为
Set-Cookie:MyUserSession = JxQoyzYm1VfESmuh-v22wyiyLREyOkuQWauziTrimjKo =; expires = Sun,10 Feb 2013 22:08:47 GMT; path = / api / rest /
,因此将来有4小时的过期。
Cookie不会存储并随后发送请求(在Chrome和Firefox中测试)。我首先认为它必须是2013年2月10日,而不是2013年2月10日,但这没有什么区别。 Chrome还会在响应的Cookie标签上显示到期日为无效的日期,但这可能也是开发工具Bug 。
任何想法?
解决方案我想我找到了解决方案。因为在开发期间,我的服务器位于localhost:30002和我的网络应用程序localhost:8003,它们被认为是关于CORS的不同主机。因此,我对服务器的所有请求都受到CORS安全规则的支持,特别是具有凭证的请求。 Credentials包含该链接上指出的Cookie,因此我没有通过返回的Cookie
xhrFields:{
withCredentials:true
}
到jQuery的
$ .ajax
函数。
我添加了标题
Access-Control-Allow-Credentials :true
,并将Access-Control-Allow-Origin
标头从通配符更改为http:// localhost:8003
(端口号是重要的!)。该解决方案现在适用于我,并存储cookie。I have a web application that uses jQuery.ajax to perform a request to another host (right now actually the same because I'm using different ports of "localhost"). The server then returns a cookie.
The cookie value in the HTTP response as shown in Chrome's Dev Tools is
Set-Cookie: MyUserSession=JxQoyzYm1VfESmuh-v22wyiyLREyOkuQWauziTrimjKo=;expires=Sun, 10 Feb 2013 22:08:47 GMT;path=/api/rest/
and so has an expiry of 4 hours in the future.
However, the cookie does not get stored and sent with subsequent requests (tested in both Chrome and Firefox). I first thought it must be "10-Feb-2013" instead of "10 Feb 2013" but that doesn't make a difference. Chrome also shows "Expires" as "Invalid date" on the cookies tab of the response, but that might as well be a Dev Tools bug.
Any ideas?
解决方案I think I found the solution. Since during development, my server is at "localhost:30002" and my web app at "localhost:8003", they are considered different hosts regarding CORS. Therefore, all my requests to the server are covered by CORS security rules, especially Requests with credentials. "Credentials" include cookies as noted on that link, so the returned cookie was not accepted because I did not pass
xhrFields: { withCredentials: true }
to jQuery's
$.ajax
function. I also have to pass that option to subsequent CORS requests in order to send the cookie.I added the header
Access-Control-Allow-Credentials: true
on the server side and changed theAccess-Control-Allow-Origin
header from wildcard tohttp://localhost:8003
(port number is significant!). That solution now works for me and the cookie gets stored.这篇关于什么可能导致不在客户端上设置Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文