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

查看:1392
本文介绍了为什么浏览器在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.)

我缺少什么?

EDIT :以下是我的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:http://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:http://192.168.1.154:3000
Referer:http://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


推荐答案

OK,所以我终于找出了问题。事实证明,当从ajax请求设置cookie时,设置 Path 选项很重要。如果您设置 Path = / ,例如:

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

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

...然后浏览器将在您导航到其他页面时发送cookie。如果不设置 Path ,浏览器将使用默认路径。显然,ajax请求的默认路径不同于导航到其他页面时使用的默认路径。我使用Go / Martini,所以在服务器端我这样做:

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

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



我猜Python / Ruby /具有类似的设置 Path 的机制。

另请参见: PHP和AJAX中的Cookie问题

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

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