如何添加express-session对象?

时间:2016-03-05 13:07:04

标签: node.js session express express-session

我想堆叠并将变量从路由器传递到另一个并堆叠它,所以我选择了express-session。这是我设计的计划。

  1. savinig req.body值为req.session.cAttr obj。
  2. 移至下一页并添加其他值(每个视图已连接)
  3. 在最后一个视图中,将值保存到mongoDB
  4. 这是app.js的一部分

     // router Setup
    app.use('/', routes);
    //app.use('/users', require('./routes/users'));
    
    app.use(session({
        resave: false,
        saveUninitialized: false,
        secret: '~~~~',
        store: new MongoStore({
            mongooseConnection: mongoose.connection
        })
    }));
    // csurf Setup
    app.use(csurf({cookie:false}));
    app.use(function(req, res, next){
        res.locals._csrfToken = req.csrfToken();
        next();
    });
    //  passport
    var passport = require('./config/passport');
    app.use(passport.initialize());
    app.use(passport.session());
    
    //  session
    app.use(function(req, res, next){
        if(req.user){
            switch (req.user.selcUniv) {
                case 1 : req.user.stringUniv = 'arg1';
                    break;
                case 2 : req.user.stringUniv = 'arg2';
                    break;
                case 3 : req.user.stringUniv = 'arg3';
                    break;
            }
        }
        res.locals.userSession = req.user;
        next();
    });
    

    路由器

    router.post('/newClassSubmit/:stage', function(req, res, next){
    var sess = req.session;
    switch (req.params.stage) {
        case 'stage_1' :
            sess.cAttr = {
                var1: req.body.D1,  //I changed key & attr name for a readability
                var2: req.body.D2
            }
            console.log(cAttr);
            res.render('newStage-2');
            break;
        case 'stage_2' :
            sess.cAttr = {
                var3: req.body.D3,
                var4: req.body.D4,
                var5: req.body.D5,
                var6: req.body.D6
            }
            res.render('newStage-3');
            break;
        case 'stage_3' :
            sess.cAttr = {
                var7: req.body.D7,
                var8: req.body.D8
            }
            res.render('newStage-4');
            break;
        case 'stage_4' :
            cModel.create(sess.cAttr);
            delete sess.cAttr;
            res.render('stage-end');
            break;
    }
    });
    

    并表达打印出来的Cannot set property of 'cAttr' undefined.

0 个答案:

没有答案