server.js
var express=require('./config/express');
var app=express();
app.listen(3000);
expressjs
var express=require('express'),
cookieParser = require('cookie-parser'),
session=require('express-session');
var app=express();
var routes=require('../app/routes/index.server.routes');
routes(app);
app.use(cookieParser());
app.use(session({
saveUninitialized: true,
resave: true,
secret: "This is a secret"
}));
routes.js
module.exports=function(app){
var indexController=require('../controllers/index.server.controller');
app.get('/',indexController.render);
}
控制器
exports.render=function(request,response){
if(request.session.lastVisit){
console.log(request.session.lastVisit);
}
request.session.lastVisit=new Date();
response.render('index',{
model:'lokesh'
})
}
错误
Cannot set property 'lastVisit' of undefined
at exports.render (C:\Users\lokesh.cherukuri\Desktop\Node\app\controllers\index.server.controller.js:9:30)
at Layer.handle [as handle_request] (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\layer.js:76:5)
at next (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\route.js:100:13)
at Route.dispatch (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\route.js:81:3)
at Layer.handle [as handle_request] (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\layer.js:76:5)
at C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\index.js:227:24
at Function.proto.process_params (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\index.js:305:12)
at C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\index.js:221:12
at Function.match_layer (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\index.js:288:3)
at next (C:\Users\lokesh.cherukuri\Desktop\Node\node_modules\express\lib\router\index.js:182:10)
我安装了所需的模块。它仍然无法创建会话。谁能指出错误。更新完整代码
答案 0 :(得分:4)
注册中间件后注册路线:
var app=express();
var routes=require('../app/routes/index.server.routes');
app.use(cookieParser());
app.use(session({
saveUninitialized: true,
resave: true,
secret: "This is a secret"
}));
routes(app);