node.js 在 Express 中设置客户端可访问的 Cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10966689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Client-Side Accessible Cookie In Express
提问by dshipper
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:
我正在开发一个使用 Express 和 SocketIO 的 Node 应用程序。我想在我的 Express 控制器中设置一个 cookie,然后可以从我的客户端 Javascript 代码访问它。我尝试的一切似乎都不起作用:
res.setHeader('Set-Cookie','test=value');
res.cookie('rememberme', 'yes', { maxAge: 900000 });
Is there something I'm missing here? Thanks in advance!
有什么我在这里想念的吗?提前致谢!
回答by dshipper
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:
弄清楚了!默认情况下,Express 将选项 httpOnly 设置为 true。这意味着客户端 Javascript 无法访问您的 cookie。为了正确设置客户端可访问的 cookie,只需使用如下代码片段:
res.cookie('rememberme', 'yes', { maxAge: 900000, httpOnly: false});
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.
我还注意到如果你调用这个命令然后调用 res.redirect,cookie 将不会被设置。这个命令需要在某个时候跟在 res.render 之后才能工作。不知道这是为什么。
回答by ehe888
Actually I have experienced the same issue for couple of hours.
实际上,我已经经历了几个小时的相同问题。
Here is my code:
这是我的代码:
res.cookie("mycookie", "1234567890", { secure:true, maxAge:120000, httpOnly: true });
I can see the Set-Cookie instruction in response header, but in Chrome I can not find the cookie and I can not find the cookie by req.cookies['mycookie'].
我可以在响应标头中看到 Set-Cookie 指令,但在 Chrome 中我找不到 cookie,我也无法通过 req.cookies['mycookie'] 找到 cookie。
The root cause of this problem is that I did not use HTTPS connection. (Express 4.x with cookie-parser middleware)
这个问题的根本原因是我没有使用HTTPS连接。(带有 cookie 解析器中间件的 Express 4.x)
According to this document: Simple Steps to Secure Your Express Node App
根据此文档:保护您的 Express 节点应用程序的简单步骤
If I set the option secure=true, then the browser will not send my cookie in any HTTP request but HTTPS secure connection. Then after I removed secure:true option, I got my cookie work.
如果我设置选项 secure=true,那么浏览器将不会在任何 HTTP 请求中发送我的 cookie,而是 HTTPS 安全连接。然后在我删除了 secure:true 选项后,我的 cookie 工作了。
回答by user13548
so to access in http can we use:
所以要在 http 中访问,我们可以使用:
res.cookie("mycookie", "1234567890", { secure:false, maxAge:120000, httpOnly: true });?

