为什么浏览器在 AJAX 请求返回后不设置 cookie? [英] Why is the browser not setting cookies after an AJAX request returns?

查看:45
本文介绍了为什么浏览器在 AJAX 请求返回后不设置 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 $.ajax 发出 ajax 请求.响应设置了 Set-Cookie 标头(我已经在 Chrome 开发工具中验证了这一点).但是,浏览器在收到响应后不会设置 cookie!当我导航到我的域中的另一个页面时,不会发送 cookie.(注意:我没有做任何跨域ajax请求;请求与文档在同一个域中.)

I am making an ajax request using $.ajax. The response has the Set-Cookie header set (I've verified this in the Chrome dev tools). However, the browser does not set the cookie after receiving the response! When I navigate to another page within my domain, the cookie is not sent. (Note: I'm not doing any cross-domain ajax requests; the request is in the same domain as the document.)

我错过了什么?

编辑:这是我的ajax请求的代码:

EDIT: Here is the code for my ajax request:

$.post('/user/login', JSON.stringify(data));

这是请求,如 Chrome 开发工具所示:

Here is the request, as shown by the Chrome dev tools:

Request URL:https://192.168.1.154:3000/user/login
Request Method:POST
Status Code:200 OK

Request Headers:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:35
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
DNT:1
Host:192.168.1.154:3000
Origin:https://192.168.1.154:3000
Referer:https://192.168.1.154:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
X-Requested-With:XMLHttpRequest

Form Data:
{"UserId":"blah","Password":"blah"}:

回复:

Response Headers:
Content-Length:15
Content-Type:application/json; charset=UTF-8
Date:Sun, 16 Mar 2014 03:25:24 GMT
Set-Cookie:SessionId=MTM5NDk0MDMyNHxEdi1CQkFFQ180SUFBUkFCRUFBQVRfLUNBQUVHYzNSeWFXNW5EQXNBQ1ZObGMzTnBiMjVKWkFaemRISnBibWNNTGdBc1ZFcDNlU3RKVFdKSGIzQlNXRkkwVjJGNFJ6TlRVSHA0U0ZJd01XRktjMDF1Y1c1b2FGWXJORzV4V1QwPXwWf1tz-2Fy_Y4I6fypCzkMJyYxhgM3LjVHGAlKyrilRg==; HttpOnly

推荐答案

好的,我终于找到了问题所在.事实证明,在 AJAX 请求中发送 cookie 时,设置 Path 选项很重要.如果你设置 Path=/,例如:

OK, so I finally figured out the problem. It turns out that setting the Path option is important when sending cookies in an AJAX request. If you set Path=/, e.g.:

Set-Cookie:SessionId=foo; Path=/; HttpOnly

...然后浏览器将在您导航到不同页面时设置 cookie.不设置Path,浏览器使用默认"路径.显然,AJAX 请求设置的 cookie 的默认路径与直接导航到页面时使用的默认路径不同.我正在使用 Go/Martini,所以在服务器端我这样做:

...then the browser will set the cookie when you navigate to a different page. Without setting Path, the browser uses the "default" path. Apparently, the default path for a cookie set by an AJAX request is different from the default path used when you navigate to a page directly. I'm using Go/Martini, so on the server-side I do this:

session.Options(session.Options{HttpOnly: true, Path:"/"})

我猜想 Python/Ruby/etc.有类似的设置Path的机制.

I'd guess that Python/Ruby/etc. have a similar mechanism for setting Path.

另见:PHP 和 AJAX 中的 cookie 问题

这篇关于为什么浏览器在 AJAX 请求返回后不设置 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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