在通过$.ajax()登录到一个网站后,我试图向该网站发送第二个$.ajax()请求-但当我检查使用FireBug发送的报头时,请求中没有会话cookie。
我做错了什么?
在通过$.ajax()登录到一个网站后,我试图向该网站发送第二个$.ajax()请求-但当我检查使用FireBug发送的报头时,请求中没有会话cookie。
我做错了什么?
当前回答
AJAX调用仅在您调用的url与调用脚本在同一域中时发送cookie。
这可能是一个跨域问题。
也许你试图从www.domain-a.com调用一个url,而你的调用脚本在www.domain-b.com上(换句话说:你进行了跨域调用,在这种情况下浏览器不会发送任何cookie来保护你的隐私)。
在这种情况下,你的选择是:
Write a small proxy which resides on domain-b and forwards your requests to domain-a. Your browser will allow you to call the proxy because it's on the same server as the calling script.This proxy then can be configured by you to accept a cookie name and value parameter which it can send to domain-a. But for this to work you need to know the cookie's name and value your server on domain-a wants for authentication. If you're fetching JSON objects try to use a JSONP request instead. jQuery supports these. But you need to alter your service on domain-a so that it returns valid JSONP responds.
如果这能帮到你就好了。
其他回答
如果您正在localhost或localhost上的端口(如localhost:8080)上进行开发,除了上面回答中描述的步骤外,还需要确保您没有在Set-Cookie报头中传递域值。 您不能在set - cookie报头中将域设置为localhost -这是不正确的-只需省略域即可。
查看cookie在本地主机与显式域和为什么asp.net不会在本地主机创建cookie ?
加上我的设想和解决方案,说不定能帮助到别人。我在使用RESTful api时遇到过类似的情况。我的承载HTML/Script/CSS文件的Web服务器和公开api的Application server托管在同一个域中。 然而,道路是不同的。
Web服务器- mydomain/webpages/abc.html
使用abc.js将cookie设置为mycookie
应用服务器- mydomain/webapis/servicename。
对哪个API调用
我期待在我的域名/webapis/servicename的cookie,并尝试读取它,但它没有被发送。 在阅读评论从答案,我检查在浏览器的开发工具 Mycookie的路径被设置为“/webpages”,因此在服务调用中不可用
mydomain webapis / xml数据
所以当设置cookie从jquery,这是我所做的-
$.cookie("mycookie","mayvalue",{**path:'/'**});
在尝试了其他解决方案后,仍然没有奏效,我发现了我的问题所在。我把contentType从“application/json”改为“text/plain”。
$.ajax(fullUrl, {
type: "GET",
contentType: "text/plain",
xhrFields: {
withCredentials: true
},
crossDomain: true
});
我有同样的问题,做一些检查我的脚本只是没有得到sessionid cookie。
通过查看浏览器中的sessionid cookie值,我发现我的框架(Django)将sessionid cookie以HttpOnly作为默认值传递。这意味着脚本不能访问sessionid值,因此不能将它与请求一起传递。有点荒谬的是,HttpOnly将是默认值,而很多东西都使用Ajax,这将需要访问限制。
为了解决这个问题,我改变了一个设置(SESSION_COOKIE_HTTPONLY=False),但在其他情况下,它可能是cookie路径上的“HttpOnly”标志
AJAX调用仅在您调用的url与调用脚本在同一域中时发送cookie。
这可能是一个跨域问题。
也许你试图从www.domain-a.com调用一个url,而你的调用脚本在www.domain-b.com上(换句话说:你进行了跨域调用,在这种情况下浏览器不会发送任何cookie来保护你的隐私)。
在这种情况下,你的选择是:
Write a small proxy which resides on domain-b and forwards your requests to domain-a. Your browser will allow you to call the proxy because it's on the same server as the calling script.This proxy then can be configured by you to accept a cookie name and value parameter which it can send to domain-a. But for this to work you need to know the cookie's name and value your server on domain-a wants for authentication. If you're fetching JSON objects try to use a JSONP request instead. jQuery supports these. But you need to alter your service on domain-a so that it returns valid JSONP responds.
如果这能帮到你就好了。