在Express中设置客户端可访问Cookie [英] Set Client-Side Accessible Cookie In Express

查看:121
本文介绍了在Express中设置客户端可访问Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用Express和SocketIO的Node应用程序。我想在我的Express控制器中设置一个cookie,然后可以从我的客户端Javascript代码访问。我尝试的一切似乎不工作:

I'm working on a Node app that uses Express and SocketIO. I want to set a cookie in my Express controller which is then accessible from my client-side Javascript code. Everything that I try doesn't seem to work:

res.setHeader('Set-Cookie','test=value');
res.cookie('rememberme', 'yes', { maxAge: 900000 });

这里有我遗漏的东西吗?先感谢!

Is there something I'm missing here? Thanks in advance!

推荐答案

想想吧!默认情况下Express将选项httpOnly设置为true。这意味着客户端Javascript无法访问您的Cookie。要正确设置客户端上可访问的Cookie,只需使用如下代码段:

Figured it out! By default Express sets the option httpOnly to true. This means that your cookies cannot be accessed by the client-side Javascript. In order to correctly set cookies accessible on the client just use a snippet like the following:

res.cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false});

我也注意到,如果你调用这个命令,然后调用res.redirect,不设置。这个命令需要在某个时间点后跟res.render,以便它工作。不确定为什么会这样。

I've also noticed that if you call this command and then call res.redirect, the cookie won't get set. This command needs to be followed by res.render at some point in order for it to work. Not sure why this is.

这篇关于在Express中设置客户端可访问Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆