【发布时间】:2017-10-18 11:21:41
【问题描述】:
在我的客户端,我在用户的 cookie 中保存了一个令牌:
this.socket.on('server:authentication', function(tokenObject){
if(tokenObject){
sessionStorage.setItem("token", tokenObject);
this.setState({ submitted: true});
}
}.bind(this));
然后我想在服务器端读取该令牌,但是当我这样做时:
app.use(cookieParser());
app.use(function(req, res, next){
const { token } = req.cookies;
console.log(token);
...
});
我在控制台上得到“未定义”。当我尝试console.log(req.cookies.token) 时也是如此。我怎样才能做到这一点?
【问题讨论】:
-
您是否将所需的 cookie 附加到 HTTP 请求?当您致电
req.cookies时,您正在检查附加到该请求的 cookie。仅仅因为 cookie 已在客户端设置,并不意味着它们会自动附加到您的 HTTP 请求中。 -
不,我没有附加我坚持的 cookie 它是自动制作的。如何让客户端发送他的 cookie?
-
这取决于您用来发出请求的内容,但我猜您可能需要将
withCredentials设置为 true。例如,here's how to do it with jQuery