Node.js表示:为什么我不能读取cookie?

时间:2017-09-04 11:48:59

标签: node.js express cookies

我写了一个非常简单的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请求,该文件就会被&#39; hello.html&#39;是送达客户的。浏览器保存cookie&#34; username = John Doe&#34;并将AJAX请求发送到端点localhost:3000 / ajax。我的目的是阅读服务器中cookie的内容(我知道cookie是从客户端自动发送的)。但是,req.cookies [&#34; username&#34;]返回undefined。

你知道为什么吗?

1 个答案:

答案 0 :(得分:2)

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