expression session how does it work

时间:2017-11-02 15:41:30

标签: node.js

I am reading an article about nodejs express module and sessions here

https://www.codementor.io/emjay/how-to-build-a-simple-session-based-authentication-system-with-nodejs-from-scratch-6vn67mcy3

I am confused on this portion of the code

app.use((req, res, next) => {
    if (req.cookies.user_sid && !req.session.user) {
        res.clearCookie('user_sid');        
      }
    next(); 
});

from where did the req object get the user property ?

If we look at the article the session object is created like

app.use(session({
    key: 'user_sid',
    secret: 'somerandonstuffs',
    resave: false,
    saveUninitialized: false,
    cookie: {
        expires: 600000
    }

So how does this even work if (req.cookies.user_sid && !req.session.user)

how does the req.cookies.user_id shouldnt it be req.cookies.key ?

How does req.session.user work ?

user is not even a property of the session object no ?

1 个答案:

答案 0 :(得分:0)

在文章中进一步了解。有几个req.userlvalue的情况。事实上,完全取决于你分配它:

文章假定这个代码块:

注册:

// route for user signup
app.route('/signup')
    .get(sessionChecker, (req, res) => {
        res.sendFile(__dirname + '/public/signup.html');
    })
    .post((req, res) => {
        User.create({
            username: req.body.username,
            email: req.body.email,
            password: req.body.password
        })
        .then(user => {
            /*
             * The user just signed up, so let's sign him in
             */
            req.session.user = user.dataValues;
            res.redirect('/dashboard');
        })
        .catch(error => {
            res.redirect('/signup');
        });
    });

登录:

// route for user Login
app.route('/login')
    .get(sessionChecker, (req, res) => {
        res.sendFile(__dirname + '/public/login.html');
    })
    .post((req, res) => {
        var username = req.body.username,
            password = req.body.password;

        User.findOne({ where: { username: username } }).then(function (user) {
            if (!user) {
                res.redirect('/login');
            } else if (!user.validPassword(password)) {
                res.redirect('/login');
            } else {
                /*
                 * The user just logged in so lets sessionize them
                 */
                req.session.user = user.dataValues;
                res.redirect('/dashboard');
            }
        });
    });