node.js - Express js session 未定义

标签 node.js express

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);
}

Controller

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\phani\Desktop\Node\app\controllers\index.server.controller.js:9:30)
   at Layer.handle [as handle_request] (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\layer.js:76:5)
   at next (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\route.js:100:13)
   at Route.dispatch (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\route.js:81:3)
   at Layer.handle [as handle_request] (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\layer.js:76:5)
   at C:\Users\phani\Desktop\Node\node_modules\express\lib\router\index.js:227:24
   at Function.proto.process_params (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\index.js:305:12)
   at C:\Users\phani\Desktop\Node\node_modules\express\lib\router\index.js:221:12
   at Function.match_layer (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\index.js:288:3)
   at next (C:\Users\phani\Desktop\Node\node_modules\express\lib\router\index.js:182:10)

我安装了所需的模块。但它仍然无法创建 session 。有人可以指出错误吗?更新了完整代码

最佳答案

注册中间件后注册您的路由:

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);

关于node.js - Express js session 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656885/

相关文章:

javascript - 将 url slug 添加到 Next Js 路由获取 TypeError 路径应该是类型字符串获取类型对象

javascript - 使用 log4js 运行 logger.js 时 logger.setLevel 不是函数

javascript - 从 Neo4j 解析复杂的 JSON 结果

javascript - 创建新事件时尝试将事件 ID 保存给创建它的用户...错误

node.js - Mongoose是否支持固定队列数组的概念

javascript - 将 JSON 数据从 AngularJS 客户端发送到 Express 服务器

javascript - Meteor 助手出错

javascript - 在 Node.js 中创建 MongoDB 服务器并将其与 Mongoose 一起使用

node.js - 将 expressjs 与 esbuild bundle 在一起会给出缺少 view.js 的警告

javascript - 如何修复 pg-promise 错误 "Promise library must be specified."?