node.js 如何使用express框架在节点js中设置cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16209145/
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
How to set cookie in node js using express framework?
提问by sachin
In my application, I need to set a cookie using the express framework.I have tried the following code but it's not setting the cookie.
在我的应用程序中,我需要使用 express 框架设置 cookie。我尝试了以下代码,但它没有设置 cookie。
Can anyone help me to do this?
谁能帮我做到这一点?
var express = require('express'), http = require('http');
var app = express();
app.configure(function(){
app.use(express.cookieParser());
app.use(express.static(__dirname + '/public'));
app.use(function (req, res) {
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cokkieName',randomNumber, { maxAge: 900000, httpOnly: true })
console.log('cookie have created successfully');
});
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(5555);
回答by robertklep
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
在 Express 中使用中间件的顺序很重要:前面声明的中间件将首先被调用,如果它可以处理请求,则后面声明的任何中间件都不会被调用。
If express.staticis handling the request, you need to move your middleware up:
如果express.static正在处理请求,则需要将中间件向上移动:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to eitherend a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()when the cookie has been set.
此外,中间件需求要么端的请求(通过发回的响应),或请求传递到下一个中间件。在这种情况下,我通过next()在设置 cookie 时调用来完成后者。
Update
更新
As of now the cookie parser is a seperate npm package, so instead of using
截至目前,cookie 解析器是一个单独的 npm 包,因此不要使用
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parserand then use it as:
您需要使用单独安装它npm i cookie-parser,然后将其用作:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
回答by Wayne Chiu
Set Cookie?
设置饼干?
res.cookie('cookieName', 'cookieValue')
Read Cookie?
读饼干?
req.cookies
Demo
演示
const express('express')
, cookieParser = require('cookie-parser'); // in order to read cookie sent from client
app.get('/', (req,res)=>{
// read cookies
console.log(req.cookies)
let options = {
maxAge: 1000 * 60 * 15, // would expire after 15 minutes
httpOnly: true, // The cookie only accessible by the web server
signed: true // Indicates if the cookie should be signed
}
// Set cookie
res.cookie('cookieName', 'cookieValue', options) // options is optional
res.send('')
})
回答by Green
Not exactly answering your question, but I came across your question, while looking for an answer to an issue that I had. Maybe it will help somebody else.
不完全回答您的问题,但我在寻找我遇到的问题的答案时遇到了您的问题。也许它会帮助别人。
My issue was that cookies were set in server response, but were not saved by the browser.
我的问题是 cookie 是在服务器响应中设置的,但没有被浏览器保存。
The server response came back with cookies set:
服务器响应返回并设置了 cookie:
Set-Cookie:my_cookie=HelloWorld; Path=/; Expires=Wed, 15 Mar 2017 15:59:59 GMT
This is how I solved it.
我就是这样解决的。
I used fetchin the client-side code. If you do not specify credentials: 'include'in the fetchoptions, cookies are neither sent to server nor saved by the browser, even though the server response sets cookies.
我fetch在客户端代码中使用。如果您没有credentials: 'include'在fetch选项中指定,cookie 既不会发送到服务器,也不会被浏览器保存,即使服务器响应设置了 cookie。
Example:
例子:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
return fetch('/your/server_endpoint', {
method: 'POST',
mode: 'same-origin',
redirect: 'follow',
credentials: 'include', // Don't forget to specify this if you need cookies
headers: headers,
body: JSON.stringify({
first_name: 'John',
last_name: 'Doe'
})
})
I hope this helps somebody.
我希望这对某人有帮助。
回答by spencer.sm
Set a cookie:
设置一个cookie:
res.cookie('cookie', 'monster')
https://expressjs.com/en/4x/api.html#res.cookie
https://expressjs.com/en/4x/api.html#res.cookie
Read a cookie:
(using cookie-parsermiddleware)
读取 cookie:(
使用cookie-parser中间件)
req.cookies['cookie']

