无法在Layer.session – ExpressJS会话中读取未定义的属性“connect.sid”

在ExpressJS 4中使用会话时遇到问题。

我曾尝试在server.js(我设置我的应用程序的configuration)和routes.js(我定义我的路线)中添加会话。 这是我一直得到的:

TypeError: Cannot read property 'connect.sid' of undefined at Layer.session [as handle] (/Users/larissaleite/Documents/Routing/node_modules/express-session/index.js:115:32) at trim_prefix (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:226:17) at c (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:198:9) at Function.proto.process_params (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:251:12) at next (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:189:19) at Layer.expressInit [as handle] (/Users/larissaleite/Documents/Routing/node_modules/express/lib/middleware/init.js:23:5) at trim_prefix (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:226:17) at c (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:198:9) at Function.proto.process_params (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:251:12) at next (/Users/larissaleite/Documents/Routing/node_modules/express/lib/router/index.js:189:19) 

我这样定义会话(server.js):

 var express = require('express'); var app = express(); // create app with express var connect = require('connect'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var passport = require('passport'); var session = require('express-session'); connect() .use(cookieParser('appsecret')) .use(function(req, res, next){ res.end(JSON.stringify(req.cookies)); }); app.use(session({ secret: 'appsecret', saveUninitialized: true, cookie: { secure: true, maxAge: new Date(Date.now() + 3600000) }, key:'connect.sid' })); 

我也尝试删除密钥。

当试图在routes.js中定义会话时,它是这样的:

 app.use(session({ secret: 'appsecret', saveUninitialized: true, cookie: { secure: true, maxAge: new Date(Date.now() + 3600000) }, key:'connect.sid' })); app.use(passport.initialize()); app.use(passport.session()); 

       

网上收集的解决方案 "无法在Layer.session – ExpressJS会话中读取未定义的属性“connect.sid”"

删除连接在一起。 Express 4是一次彻底的彻底改变,将连接作为依赖关系去除。 删除所有需要/呼叫连接的部分。 同时更新所有的依赖关系。

根据快速会话中间件模块的文档: name - cookie name (formerly known as key). (default: 'connect.sid') name - cookie name (formerly known as key). (default: 'connect.sid')

不要传递任何东西,它会使用快速sid。 我已经复制了你的代码,并没有连接testing它,我没有得到这些错误。 此外,我已将resave密钥添加到sessionconfiguration对象,以将不推荐使用的警告(如果您正在运行最新的express 4版本)静音。

 var express = require('express'); var app = express(); // create app with express var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var passport = require('passport'); var session = require('express-session'); app.use(session({ secret: 'appsecret', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: new Date(Date.now() + 3600000) } })); app.listen(1234);