gpt4 book ai didi

Node.js express : why can't I read cookies ?

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:28 26 4
gpt4 key购买 nike

我写了一个非常简单的node.js服务器:

var express = require('express');
var cookieParser = require("cookie-parser");

var app = express();
app.use(cookieParser());

app.get('/', function(req, res){
res.sendFile(__dirname + "/hello.html");
});

app.get('/ajax', function(req, res) {
console.log('ajax request received');
console.log(req.cookies["username"])
})
app.listen(3000);

和一个非常简单的客户端 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> Hello World </h1>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
document.cookie = "username=John Doe";
$.ajax({
url: "http://127.0.0.1:3000/ajax",
}).done(function() {
alert('AJAX sent');
});
</script>
</body>
</html>

正如您所理解的,一旦服务器运行并且最终用户向 localhost:3000 发送 get 请求,文件“hello.html”就会被提供给客户端。浏览器保存 cookie“username=John Doe”并向端点 localhost:3000/ajax 发送 AJAX 请求。我的目的是读取服务器中cookie的内容(我知道cookie是从客户端自动发送的)。但是,req.cookies["username"] 返回未定义。

你知道为什么吗?

最佳答案

问题是我向 localhost:3000 发送了 GET 请求,因此 cookie 保存在域 http://localhost 中。但是,当我向 127.0.0.1 发送 AJAX 调用时,不会发送 cookie,因为浏览器将 127.0.0.1 和 localhost 视为不同的域。因此,使用127.0.0.1:3000(而不是localhost:3000)打开浏览器即可解决。

关于Node.js express : why can't I read cookies ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46036408/

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