Sessions in Node JS

前端 未结 10 858
北海茫月
北海茫月 2021-01-07 23:46

How can I maintain my SESSIONS in Node JS ? E.g I want to store UserID in SESSION using Node Js. How can I do that in Node JS ? And can I use that Node JS SESSION in PHP too

10条回答
  •  粉色の甜心
    2021-01-08 00:08

    To maintain a session is now older You should try with JWT token, It is very effective and easy. But still to maintain the session in Node js:

    In your Express Config:

    var cookieParser = require('cookie-parser');
    var session = require('express-session');
    
    app.use(cookieParser());
        app.use(session({
            secret: 'secret',
            resave: true,
            saveUninitialized: true,
            rolling: true,
            cookie: {
                path: '/',
                maxAge: 60000 * 1000
            },
            name: 'SID'
        }));
    

    Store session after Login:

    var session = req.session;
        if (user) {
            session.user = user._id;
            session.save();
            console.log(session);
        }
    

    Check Session from middleware:

    var session = req.session;
                if (session.user) {
                    req.userid = session.user;
                    next();
                } else {
                    return res.status(401).send({
                        code: 401,
                        message: Constant.authentication_fails
                    });
                }
    

    Hope you will get clear idea about session.

提交回复
热议问题