javascript 如何通过 Ajax 调用修改 Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5077998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:52:30  来源:igfitidea点击:

How to modify Cookie from Ajax call

javascriptcookiesxmlhttprequest

提问by jcubic

I have this code:

我有这个代码:

window.onload = function() {
        document.cookie = 'foo=bar; expires=Sun, 01 Jan 2012 00:00:00 +0100; path=/';
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "/showcookie.php",true);
        xhr.setRequestHeader("Cookie", "foo=quux");

        xhr.setRequestHeader("Foo", "Bar");
        xhr.setRequestHeader("Foo", "Baz");

        xhr.withCredentials = true;
        var pre = document.getElementById('output');
        xhr.onreadystatechange = function() {
            if (4 == xhr.readyState) {
                pre.innerHTML += xhr.responseText + "\n";
            }
        };
        xhr.send(null);
    };

and this /showcookie.php

和这个 /showcookie.php

<?php

print_r($_COOKIE);

?>

and it always show

它总是显示

Array
(
    [Host] => localhost
    [User-Agent] => 
    [Accept] => 
    [Accept-Language] => pl,en-us;q=0.7,en;q=0.3
    [Accept-Encoding] => gzip,deflate
    [Accept-Charset] => ISO-8859-2,utf-8;q=0.7,*;q=0.7
    [Keep-Alive] => 115
    [Connection] => keep-alive
    [foo] => Baz
    [Referer] =>
    [Cookie] => foo=bar
)

Array
(
    [foo] => bar
)

I'm using Firefox 3.6.13, Opera 11.00 and Chromium 9.0 on Ubuntu.

我在 Ubuntu 上使用 Firefox 3.6.13、Opera 11.00 和 Chromium 9.0。

Is anybody have the same problem or maybe it's impossible to modify Cookie header.

是否有人有同样的问题,或者可能无法修改 Cookie 标头。

回答by Tgr

The Cookie header is one of several which cannot be modified in an XMLHttpRequest. From the specification:

Cookie 标头是无法在XMLHttpRequest. 从规范

Terminate [execution of the setRequestHeadermethod]if header is a case-insensitive match for one of the following headers:

  • Accept-Charset
  • Accept-Encoding
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Content-Transfer-Encoding
  • Date
  • Expect
  • Host
  • Keep-Alive
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via

… or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-).

The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent. Header names starting with Sec- are not allowed to be set to allow new headers to be minted that are guaranteed not to come from XMLHttpRequest.

如果标头是以下标头之一的不区分大小写的匹配,则终止[setRequestHeader方法的执行]

  • 接受字符集
  • 接受编码
  • 联系
  • 内容长度
  • 曲奇饼
  • 饼干2
  • 内容传输编码
  • 日期
  • 预计
  • 主持人
  • 活着
  • 推荐人
  • TE
  • 预告片
  • 传输编码
  • 升级
  • 用户代理
  • 通过

... 或者如果头的开始是不区分大小写的匹配 Proxy- 或 Sec-(包括当头只是 Proxy- 或 Sec- 时)。

上述标头由用户代理控制,以使其控制传输的这些方面。这在一定程度上保证了数据的完整性。不允许设置以 Sec- 开头的标头名称以允许创建新标头,这些标头保证不是来自 XMLHttpRequest。

回答by johnhunter

I thinkthis might be a hard constraint on the XHR functionality.

认为这可能是对 XHR 功能的严格限制。

Setting the clientside document.cookie caused the Cookie header to be sent in requests as expected. If you want to pass a cookie value in an an ajax request this might be the way to go.

设置客户端 document.cookie 会导致 Cookie 标头按预期在请求中发送。如果您想在 ajax 请求中传递 cookie 值,这可能是要走的路。

A workaround is to send a custom header to the php script with the cookie string you want to set:

一种解决方法是使用您要设置的 cookie 字符串将自定义标头发送到 php 脚本:

// in the js...
xhr.open("GET", "showcookie.php",true);
//xhr.setRequestHeader("Cookie", "foo=quux");
xhr.setRequestHeader("X-Set-Cookie", "foo2=quux");

xhr.withCredentials = true;

Then in your showcookie.php you can grab the custom header value and fire a set-cookie response header:

然后在您的 showcookie.php 中,您可以获取自定义标头值并触发 set-cookie 响应标头:

$cookie = $_SERVER['HTTP_X_SET_COOKIE'];

// NOTE: really should sanitise the cookie input.
header('Set-Cookie: ' . $cookie);


print_r($_COOKIE);

Note that you wont see a cookie header until the response is parsed by the browser. Also please make sure you sanitise the contents of the X_SET_COOKIE header - this is a proof of concept only:)

请注意,在浏览器解析响应之前,您不会看到 cookie 标头。另外请确保您清理 X_SET_COOKIE 标头的内容 - 这只是一个概念证明:)