在通过$.ajax()登录到一个网站后,我试图向该网站发送第二个$.ajax()请求-但当我检查使用FireBug发送的报头时,请求中没有会话cookie。
我做错了什么?
在通过$.ajax()登录到一个网站后,我试图向该网站发送第二个$.ajax()请求-但当我检查使用FireBug发送的报头时,请求中没有会话cookie。
我做错了什么?
当前回答
在尝试了其他解决方案后,仍然没有奏效,我发现了我的问题所在。我把contentType从“application/json”改为“text/plain”。
$.ajax(fullUrl, {
type: "GET",
contentType: "text/plain",
xhrFields: {
withCredentials: true
},
crossDomain: true
});
其他回答
使用
xhrFields: { withCredentials:true }
作为我的jQuery ajax调用的一部分只是解决方案的一部分。我还需要有从我的资源的选项响应返回的头:
Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true
重要的是,OPTIONS调用的响应头中只有一个允许的“origin”,而不是“*”。我通过从请求中读取源并将其填充回响应来实现这一点——可能绕过了限制的最初原因,但在我的用例中,安全性并不是最重要的。
我认为有必要明确地提到只有一个源的要求,因为W3C标准允许空格分隔列表,但Chrome不允许! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header 注意“在实践中”的部分。
当您试图发送跨站点请求时发生此错误。 我怎么解决这个问题?
在nginx配置文件中添加
add_header Access-Control-Allow-Origin '*.domain.com'
add_header Access-Control-Allow-Credentials 'true';
在“domain.com”中,我试图发送ajax请求
$.ajax({
url: sub.domain.com,
xhrFields: {
withCredentials: true
}
});
把这个放在你的init函数中:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
它会起作用的。
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.
如果这能帮到你就好了。
在尝试了其他解决方案后,仍然没有奏效,我发现了我的问题所在。我把contentType从“application/json”改为“text/plain”。
$.ajax(fullUrl, {
type: "GET",
contentType: "text/plain",
xhrFields: {
withCredentials: true
},
crossDomain: true
});