会话对象内缺少userId变量

时间:2019-01-27 08:47:47

标签: express session-cookies express-session

我是express的新手。我正在尝试使用会话管理创建一个login,register网站。我正在使用express-session进行会话管理。

使用的版本: "express": "^4.16.4""express-session": "^1.15.6"

app.js服务器文件

const express = require("express")
const session = require("express-session")
const bodyParser = require("body-parser")
const ONE_HOUR = 1000 * 60 * 60
const {
    NODE_ENV = "development",
    SESS_NAME = "sid",
    SESS_SECRET = "kjkjs&^*%&%^(*&(*9u43jkjkl897sd",
    SESS_LIFETIME = ONE_HOUR
} = process.env
const IN_PROD = NODE_ENV === "production"
const app = express()
app.use(session({
    name: SESS_NAME,
    resave: true,
    saveUninitialized: true,
    secret: SESS_SECRET,
    cookie: {
        maxAge: SESS_LIFETIME,
        sameSite: true,
        secure: IN_PROD
    } 
}))
const cors = require("cors")
const morgan = require("morgan")
const {sequelize} = require("./models")
const config = require("./config/config")
const routes = require("./routes")

app.use(morgan("combined"))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))


//app.use(express.bodyParser())
app.use(cors())

routes.setRoutes(app)

//sequelize.sequelize.sync

sequelize.sync(/* {force:true} */)
    .then(()=> {
        app.listen(config.port)
        // console.log(x)
        console.log(`Server started on port ${config.port}`)
    })

这是我的loginregister函数的实现:

const {User} = require("../models")
const session = require("express-session")
module.exports = {
    register : async function(req,res) {
        console.log(req.body)
        let msg = `Register request for ${req.body.email} found`
        console.log(msg)
        try {
            const user = await User.create(req.body) 
            res.send(user.toJSON())
        }catch(err) {
            // email already exits
            res.status(400).send( {
                error : "This email is alread in use"
            })
        }
    },
    login : async function(req,res) {
        console.log("===================================")
        console.log("inside the login function\n\n",req.body)
        console.log(">>>>>>>>>>>session object : ",req.session)
        const userId = req.session.userId
        console.log(">>>>>>>>>>>session Id = ",userId)
        if(!userId) {
            const { userId } = req.session  
            let msg = `Login request for ${req.body.email} found`
            console.log(msg)
            try {
                const {email,password} = req.body
                const user = await User.findOne({
                    where: {
                        email: email
                    }
                })
                if(!user) {
                    return res.status(403).send({
                        error:"The login information was wrong"
                    })
                }
                const isPasswordValid = password === user.password
                if(!isPasswordValid) {
                    return res.status(403).send({
                        error:"The login information was wrong"
                    })
                }
                /* create session */
                req.session.userId = user.id + 1
                console.log(`session created for ${user.email} with sessionId = ${req.session.userId}`)
                //req.session.save()
                const userJson = user.toJSON()
                res.send({
                    msg: "The use was found OK !!",
                    user: userJson
                })
                console.log("^^^^^^^^^^^session object : ",req.session)
            }catch(err) {
                // email already exits
                res.status(500).send( {
                    error : "This email is alread in use"
                })
            }
        }else {
            console.log(`user ${req.body.email} is already logged in`)
            res.send({
                status: "Session is already created !!"
            })
        }

    }
}

它在login函数内部打印会话对象,

^^^^^^^^^^^session object :  Session {
  cookie: 
   { path: '/',
     _expires: 2019-01-27T09:31:13.078Z,
     originalMaxAge: 3600000,
     httpOnly: true,
     sameSite: true,
     secure: false },
  userId: 2 }

但是当我第二次尝试时(在login函数的顶部),变量userId丢失了。

>>>>>>>>>>>session object :  Session {
  cookie: 
   { path: '/',
     _expires: 2019-01-27T09:31:13.062Z,
     originalMaxAge: 3600000,
     httpOnly: true,
     sameSite: true,
     secure: false } }

为什么会这样?我尝试了在不同的SO线程中提供的可变解决方案。没有工作。是async/await的原因吗?请帮忙!

谢谢!

0 个答案:

没有答案