Cookies不会在HTTP GET请求中发送。

3
我正在使用HTTP Only(在生产环境中还要安全)的Cookie来维护与后端API的用户身份验证状态。
但是,我遇到了一个问题,即Cookies在HTTP GET请求中未被发送。POST和PATCH请求完美地工作,但GET缺少Cookies请求标头。
我没有看到这是标准的特定限制。Mozilla文档明确提供了一个包括Cookies的GET请求示例。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies 作为背景,我目前处于开发阶段,因此在“localhost”上运行,并使用Chrome 63.0.3239.132。
编辑:添加图像
因此,应用程序中已设置了cookie。

Cookies Set

PATCH请求按预期发送了Cookies。

Patch Working, sending cookies as expected

GET请求没有包含任何内容。我抛出了404错误,因为找不到cookie的值。

Get Not Working, no cookies are sent

1个回答

5
问题出在使用JQuery发起AJAX请求的javascript(实际上是Typescript)代码上。
Cookies被视为凭据,因此XHR请求必须允许withCredentials=true
let ajax = this.jQuery.ajax({
  type: "GET",
  url: getUrl,
  headers: this.generateHeaders(),
  xhrFields: {
    withCredentials: true // this was false.
  },
  timeout: this.options.RequestTimeoutMs
});

更改了withCredentials字段后,cookie被发送了!

附注:关于withCredentials。您需要CORS设置来允许此操作,具体而言是Access-Control-Allow-Credentials:true,此时您不能使用Access-Control-Allow-Origin:*(也不是一个好主意),而必须指定没有尾部/的域。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接