node.js - 客户端 session NodeJS/Express - 错误 : Cannot set property 'mydata' of undefined

标签 node.js session express

我尝试在 nodejs/Express 中使用客户端 session 中间件,但收到以下错误:无法设置未定义的属性“mydata”。

我也看过这篇文章,但找不到其他线索来解释为什么我可能会收到错误。 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;
    }
})

最佳答案

client-sessions 的文档解释:

cookie name dictates the key name added to the request object

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

req.firstName.mydata = req.body.mydata

关于node.js - 客户端 session NodeJS/Express - 错误 : Cannot set property 'mydata' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37620092/

相关文章:

angularjs - 在不同的服务器上序列化多个数据库

javascript - 即使在 return 语句之后代码仍在执行吗?

Node.js/Express.js session management cookie 为 session cookie

node.js - AWS Timestream - SDK V3 Nodejs,TimestreamWriteClient.send() - TypeError : command. resolveMiddleware 不是函数。如何解决这个问题?

python - 为什么调用 Flask session 时会出现 Key 错误?

javascript - 在 Express 路由器中使用 multer 进行文件上传

javascript - 使用 Node 和 FS 制作我自己的 "database"

javascript - React - '$' 未定义

php session 购物车使用插入记录项目数量两次

session - Struts 2 session 属性未在 jsp 中显示