我正在尝试为我的基于nodejs的web-app实现登录功能。
const express = require('express');
const app = express();
const route = express.router;
const sessions = require("client-sessions");
app.use(sessions({
coockieName: 'SNsession',
secret: '0GBlJZ9EKBt2Zbi2flRPvztczCewBxXK' // set this to a long random string!
}));
const user = 'john';
app.get('/login', function (req, res){
req.sessions.user = user;
});
const port = process.env.PORT || 5000;
app.listen(port, function () {
console.log("listening on " + port);
});
app.get('/', function (req, res) {
res.send('index');
});
我想看到我在Mozilla Hack的博客上看到的完全相同的结果也发生在我的电脑上。 博客文章: https://hacks.mozilla.org/2012/12/using-secure-client-side-sessions-to-build-simple-and-scalable-node-js-applications-a-node-js-holiday-season-part-3/
尽管如此,我得到了这个:
TypeError: Cannot set property 'user' of undefined
at c:\node\test\server.js:15:21
at Layer.handle [as handle_request] (c:\node\node_modules\express\lib\router\layer.js:95:5)
at next (c:\node\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\node\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\node\node_modules\express\lib\router\layer.js:95:5)
at c:\node\node_modules\express\lib\router\index.js:281:22
at Function.process_params (c:\node\node_modules\express\lib\router\index.js:335:12)
at next (c:\node\node_modules\express\lib\router\index.js:275:10)
at clientSession (c:\node\node_modules\client-sessions\lib\client-sessions.js:630:5)
at Layer.handle [as handle_request] (c:\node\node_modules\express\lib\router\layer.js:95:5)
我一直试图解决这个问题几个小时,但我还没有看到它有效。
我复制并粘贴了博客上的代码,即使没有修改它们,我也无法使其正常工作。 请帮忙:(
答案 0 :(得分:0)
替换
req.sessions.user = user;
使用
req.session.user = user;
从会话
中删除最后一个''