我已将NodeJS应用程序更新为Express 4.0,现在除了快速会话cookie之外,我无法设置自己的cookie.此问题仅发生在任何会话的第一个请求上,当用户重新加载自定义cookie所在的页面时.
var express = require('express'); var routes = require('./routes'); var http = require('http'); var path = require('path'); var session = require('express-session'); var app = express(); app.set('port',process.env.PORT || 3000); app.use(express.static(path.join(__dirname,'public'))); app.use(require('body-parser')()); app.use(require('method-override')()); app.use(require('cookie-parser')('cookie-secret')); //app.use(session({ secret: 'secret',key: 'sid'})); //uncomment this to see the problem app.get('/',function(req,res,next) { res.cookie('testing','test'); //this isn't set if using 'app.use(session...)' res.send('This is a cookie test'); }); http.createServer(app).listen(app.get('port'),function(){ console.log('Express server listening on port ' + app.get('port')); });
去测试:
1.运行上面的代码,将cookie“testing”发送到浏览器正确.
2.然后清除cookie并取消注释“app.use(session …”行.
3.运行应用程序,唯一的cookie是“sid”.哪里的“测试”?
4.重新加载页面(不清除cookie)并且存在“测试”cookie.
在第一次请求时,我的所有cookie都必须存在.
解决方法
这对我有用:
var mw = { favicon: require('static-favicon'),logger: require('morgan'),bodyParser: require('body-parser'),cookieParser: require('cookie-parser'),session: require('express-session'),methodOverride: require('method-override') }; var MongoStore = require('connect-mongo')(mw); app.store = new MongoStore(...); app.use(function(req,next) { if ('HEAD' === req.method || 'OPTIONS' === req.method) return next(); var writeHead = res.writeHead; res.writeHead = function() { res.cookie('XSRF-TOKEN',req.session && req.session._csrfSecret); writeHead.apply(res,arguments); }; next(); }); app.use(mw.session({ key: 'yourCookieID',cookie: { maxAge: 3600000 * 24 * 7 },store: app.store }));