Javascript 在 Node.js 中设置 cookie 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12240274/
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 a cookie value in Node.js
提问by Javier Manzano
I'm developing a website with node.js and express. How can I set a cookie value?
我正在用 node.js 和 express 开发一个网站。如何设置 cookie 值?
回答by Jonathan Lonowski
As Express is built on Connect, you can use the cookieParser
middlewareand req.cookies
to read and res.cookie()
to write cookies:
由于 Express 是基于Connect构建的,因此您可以使用cookieParser
中间件并req.cookies
读取和res.cookie()
写入 cookie:
// configuration
app.use(express.cookieParser());
// or `express.cookieParser('secret')` for signed cookies
// routing
app.get('/foo', function (req, res) {
res.cookie('bar', 'baz');
// ...
});
app.get('/bar', function (req, res) {
res.send(req.cookies.bar);
});
[Update]
[更新]
As of Express 4.0, Connect will no longer be included with Expressand the default middleware have been moved into their own packages, including cookie-parser
.
从 Express 4.0 开始,Connect 将不再包含在 Express 中,并且默认中间件已移动到它们自己的包中,包括cookie-parser
.
回答by MT.
You could just use the response object that express provides to set your cookies.
您可以使用 express 提供的响应对象来设置您的 cookie。
You can find detailed information on how to do that at: http://expressjs.com/en/api.html#res.cookie
您可以在以下位置找到有关如何执行此操作的详细信息:http: //expressjs.com/en/api.html#res.cookie