简体   繁体   中英

Having trouble with NodeJS session

I'm trying to implement a login function to my nodejs based 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');
});

I want to see exactly the same result that I've seen on Mozilla Hack's blog to happen on my computer as well. Blog post: 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/

Despite that, I'm getting this:

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)

I've been trying to figure this out for hours and hours but I yet to have seen it work.

I've copy and pasted the code that's on the blog, even without modifying them, I just can't make it work. Please help :(

Replace

 req.sessions.user = user;

With

 req.session.user = user;

Remove the last 's' from sessions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM