Jquery Ajax CORS + HttpOnly Cookie

时间:2011-07-04 16:18:02

标签: jquery ajax cookies cors

我有CORS在我当前的项目上工作,虽然我似乎无法正常工作的一件事就是cookies。

现在我把cookie弄好了,服务器发出它并发送它并且firefox接受它,我可以在firebug cookies部分看到它。但是,当我对该服务进行后续调用时,它似乎不会在标题中发送cookie ...

GET /some/entity/ HTTP/1.1
Host: localhost:1837
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
Accept: */*
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: http://localhost:6879
Origin: http://localhost:6879

我是否需要对我的ajax电话做一些特别的事情?

var ajaxOptions = {
    url: serviceResourceUrl,
    type: "get",
    dataType: "json",
    success: successCallback,
    error: failedCallback,
    xhrFields: { withCredentials: true }
};

$.ajax(ajaxOptions);

1 个答案:

答案 0 :(得分:9)

尝试使用beforeSend属性而不是xhrFields。在你的情况下:

var ajaxOptions = {
    url: serviceResourceUrl,
    type: "get",
    dataType: "json",
    success: successCallback,
    error: failedCallback,
    beforeSend: function(xhr){
      xhr.withCredentials = true;
    }
};

$.ajax(ajaxOptions);

您可以在此处了解详情:Sending credentials with cross-domain posts?