NODE JS会话为NULL

时间:2019-01-16 00:49:27

标签: javascript node.js express session

我创建了一个会话来在我的网站上记录用户活动。但是,即使在我具有app.use(session({...}))的情况下,我在浏览器中键入网站地址并输入该会话的会话值仍为NULL,但是在刷新/重新加载页面或转到该会话的其他页面具有正确的值。

在我的index.js中,我有以下内容:

const session = require('express-session')


const user_session = require('./middlewares/session/sessions')


app.use('/static', express.static('public'));
app.use(cookieParser('secret key');
app.use(flash());
app.use(session({
    secret: 'secret key',
    resave: false,
    saveUninitialized: true,
    store: sessionStore,
    cookie: {
        secure: false, 
        maxAge: 86400000
    }
})); 

每条路由都使用中间件user_session.session

user_session.session的代码如下:

exports.session = (req,res,next) =>{
    const pathname = parseurl(req).pathname
    const sess_id = req.session_id ? req.session_id : req.sessionID//req.session.id
    sessionStore.get(sess_id,(err,session)=>{
        if (err) console.log(err)
        else{
            console.log(session) /// THE VALUE OF session is NULL 
            if(session){
                if(!session.views){
                    session.views = {}
                }
                if(!session.activity){
                    session.activity = []
                }
                else{
                    console.log('add pathes to viwes and activity')
                    session.views[pathname] = (session.views[pathname] || 0) + 1
                    session.activity.push(pathname)
                }
                sessionStore.set(sess_id,session,(err => console.log(err)))
                console.log(`${sess_id} -> ${pathname}`)
            }
        }
        return next()
    })
    //return next()
}

0 个答案:

没有答案