gpt4 book ai didi

node.js - 使用 XMLHttpRequest 2 设置 Cookie

转载 作者:太空宇宙 更新时间:2023-11-04 00:50:59 26 4
gpt4 key购买 nike

我正在尝试使用 XMLHttpRequest 设置 cookie。我在对 XHR post 请求的响应中看到“Set-Cookie” header ,但在 document.cookie 中没有看到 cookie。不过,这很好,我最终希望 cookie 不暴露在 javascript 环境中,但我没有看到任何 cookie 附加到脚本的任何后续 post 请求,并且我认为 cookie 是自动附加到浏览器的请求的。这是不正确的吗?我对 cookie 是否被设置有点困惑,我可以使用一些帮助来解决这个问题。

客户端代码如下:

(function() {
var xhr = new XMLHttpRequest();
var authUrl= "http://api.myserver.io/cookie"
xhr.addEventListener("load", reqListener);
xhr.open("POST", authUrl, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.credentials = true;
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
debugger;
// I'm not seeing anything in xhr.request
}
}
var reqListener = function() {
debugger;
}
})()

服务器代码正在利用expressess并使用此函数处理请求:

var setCookie = function(req, res) {
res.cookie('test-cookie', Date.now(), {
maxAge: 3600000000,
path: '/' });
res.status(200).end()
}

最佳答案

我需要设置xhr.withCredentials = true,而不是xhr.credentials = true

关于node.js - 使用 XMLHttpRequest 2 设置 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32447257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com