【发布时间】:2017-09-04 11:48:59
【问题描述】:
我写了一个非常简单的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"] 返回未定义。
你知道为什么吗?
【问题讨论】:
-
您没有指定 cookie 应该有效的路径......因此它可能根本不适用于路径
/ajax。使用您的浏览器开发工具来验证 cookie 的路径是什么。