在我的应用程序中,我需要使用express框架设置cookie。我已经尝试了以下代码,但没有设置cookie。
谁能帮我做到这一点?
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);
在Express中使用中间件的顺序很重要:先前声明的中间件将首先被调用,并且如果它可以处理请求,则稍后声明的任何中间件都不会被调用。
如果express.static正在处理请求,则需要向上移动中间件:
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'));
此外,中间件需求 要么 端的请求(通过发回的响应),或请求传递到下一个中间件。在这种情况下,我通过next()在设置cookie时调用来完成后者。
next()
更新资料
到目前为止,cookie解析器是一个单独的npm包,因此不要使用
app.use(express.cookieParser());
您需要使用单独安装它npm i cookie-parser,然后将其用作:
npm i cookie-parser
const cookieParser = require('cookie-parser'); app.use(cookieParser());