client-sessions nodejs / Express - 错误:无法设置属性' mydata'未定义的

时间:2016-06-03 17:14:03

标签: node.js session express

我试图在nodejs / Express中使用客户端会话中间件,我收到以下错误:Cannot set property 'mydata' of undefined.

我也看过这篇文章,但是找不到更多关于我为什么会收到错误的线索。 node-js-client-sessions-not-creating-req-session

var bodyParser = require('body-parser');
const express = require('express');

const app = express();
const clientSessions = require("client-sessions");

var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();

app.use(clientSessions({
  cookieName: 'mydata', // cookie name dictates the key name added to the request object
  secret: 'longsecretkeyorwhatever', // should be a large unguessable string
  duration: 24 * 60 * 60 * 1000, // how long the session will stay valid in ms
  activeDuration: 1000 * 60 * 5 // if expiresIn < activeDuration, the session will be extended by activeDuration milliseconds
}));

/* Form POST handler */
router.post('/', urlencodedParser, function(req, res) {
    if (!req.body) return res.sendStatus(400);

    if(req.body.firstName){
        req.session_state.mydata = req.body.mydata;
    }
})

1 个答案:

答案 0 :(得分:1)

client-sessions的文档解释了:

  

cookie name指示添加到请求对象的密钥名称

由于您将firstName设置为Cookie名称,因此会话对象可用req.firstName

req.firstName.mydata = req.body.mydata