使用 XMLHttpRequest2 设置 Cookie
Setting Cookies with XMLHttpRequest2
我正在尝试使用 XMLHttpRequest 设置 cookie。我在对 XHR post 请求的响应中看到 "Set-Cookie" header,但我在 document.cookie 中没有看到 cookie。不过没关系,我最终希望 cookie 不暴露在 javascript 环境中,但我没有看到任何附加到脚本的任何后续 post 请求的 cookie,我认为 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;
}
})()
服务器代码正在使用 express 并使用此函数处理请求:
var setCookie = function(req, res) {
res.cookie('test-cookie', Date.now(), {
maxAge: 3600000000,
path: '/' });
res.status(200).end()
}
我需要设置 xhr.withCredentials = true
,而不是 xhr.credentials = true
我正在尝试使用 XMLHttpRequest 设置 cookie。我在对 XHR post 请求的响应中看到 "Set-Cookie" header,但我在 document.cookie 中没有看到 cookie。不过没关系,我最终希望 cookie 不暴露在 javascript 环境中,但我没有看到任何附加到脚本的任何后续 post 请求的 cookie,我认为 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;
}
})()
服务器代码正在使用 express 并使用此函数处理请求:
var setCookie = function(req, res) {
res.cookie('test-cookie', Date.now(), {
maxAge: 3600000000,
path: '/' });
res.status(200).end()
}
我需要设置 xhr.withCredentials = true
,而不是 xhr.credentials = true