【问题标题】:How can I set cookies to an HTTP Request?如何将 cookie 设置为 HTTP 请求?
【发布时间】:2018-01-03 22:34:31
【问题描述】:

我需要为 HTTP 请求设置 cookie。

有可能做这样的事情吗?

$.ajax({
    method: "POST",
    url: "http://example.org/",
    dataType: "html",
    data: {
        game: "soccer",
        value: "2395",
        action: "newGame"
    },
    cookies: {
        "domain": ".example.org",
        "name": "SESSION",
        "path": "/",
        "value": "34645645765756757"
    }
}).done(function( msg ) {
    console.log(msg);
});

【问题讨论】:

  • 不,这是不可能的。它会发送 document.cookie 中的任何 cookie(假设 URL 在同一个域中)。
  • 如果您想发送 cookie,只需将它们作为参数或标头发送即可。

标签: javascript jquery cookies httprequest


【解决方案1】:

您不必在请求中显式添加 cookie,它会发送您当前拥有的 cookie。

如果您尝试链接到另一个网站,您需要设置 HTTP 跨域访问:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

并使用

$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});

您也可以尝试在请求之前重置 Cookie 标头

$.ajax({
  //...
  beforeSend: function(request) {
    request.setRequestHeader("Cookie", "name=value; name2=value2; name3=value3");
  },
  //...
});

【讨论】:

    【解决方案2】:

    将自动为所有相同的域请求发送和接收 Cookie。

    如果您需要发送和接收跨域cookie设置withCredentials。您无法控制这些 cookie 是什么

    $.ajax({
       url: a_cross_domain_url,
       xhrFields: {
          withCredentials: true
       }
       //... other options
    });
    

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 2011-06-24
      • 2014-08-23
      • 2020-09-26
      • 2016-12-10
      • 2017-12-22
      相关资源
      最近更新 更多