Node.js - Express会话数据不会持久化

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node.js - Express会话数据不会持久化相关的知识,希望对你有一定的参考价值。

登录按预期工作并返回会话数据但超出此范围我无法保持会话数据。例如,当我调用getUser(下面)时,不会返回会话数据。

app.js(设置)

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const request = require('request')
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);

const app = express()
app.use(morgan('combined'))
app.use(bodyParser.json())
app.use(cors({
    credentials: true
}))

const mongodb_conn_module = require('./mongodbConnModule');
var db = mongodb_conn_module.connect();

app.use(session({
    secret: 'work hard',
    resave: false,
    saveUninitialized: true,
    cookie: {
        secure: false,
        maxAge: 24 * 60 * 60 * 1000
    },
    store: new MongoStore({
        mongooseConnection: db,
        ttl: 24 * 60 * 60 // Keeps session open for 1 day
    })
}));

app.js(登录)

app.post('/login', (req, res) => {
    if (req.body.logEmail && req.body.logPassword) {
        Users.authenticate(req.body.logEmail, req.body.logPassword, function (error, user) {
            if (error || !user) {
                var err = new Error('Wrong email or password.');
                err.status = 401;
                res.send("Wrong email or password.");
            } else {
                req.session.userId = user._id;
                res.send({
                    success: true,
                    sessionInfo: req.session
                });
            }
        });
    } else {
        var err = new Error('All fields required.');
        err.status = 400;
        res.send("All fields required.");
    }
})

返回会话数据(userId)enter image description here

app.js(getUser)

app.get('/get_user', (req, res) => {
    res.send(req.session)
})

这似乎会丢掉会话数据enter image description here

UsersService.js(型号)

var mongoose = require("mongoose");
var bcrypt = require('bcrypt');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    userName: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    email: {
        type: String,
        unique: true,
        required: true,
        trim: true
    },
    password: {
        type: String,
        required: true,
    },
    passwordConf: {
        type: String,
        required: true,
    }
});

//authenticate input against database
UserSchema.statics.authenticate = function (email, password, callback) {
    Users.findOne({ email: email })
        .exec(function (err, user) {
            if (err) {
                return callback(err)
            } else if (!user) {
                var err = new Error('User not found.');
                err.status = 401;
                return callback(err);
            }
        bcrypt.compare(password, user.password, function (err, result) {
            if (result === true) {
                return callback(null, user);
            } else {
                return callback();
            }
        })
    });
}

// hashing a password before saving it to the database
UserSchema.pre('save', function (next) {
    var user = this;
    bcrypt.hash(user.password, 10, function (err, hash) {
        if (err) {
            return next(err);
        }
        user.password = hash;
        next();
    })
});

var Users = mongoose.model("Users", UserSchema);
module.exports = Users;

提前致谢!

答案

我刚刚经过大量的工作后解决了同样的问题,因为在app.js(设置)中订单不好,所以通过这段代码编辑app.js(设置)希望能帮到你:)

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const request = require('request')
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);

const app = express()
    app.use(session({
            secret: 'work hard',
            resave: false,
            saveUninitialized: true,
            cookie: {
                secure: false,
                maxAge: 24 * 60 * 60 * 1000
            },
            store: new MongoStore({
                mongooseConnection: db,
                ttl: 24 * 60 * 60 // Keeps session open for 1 day
            })
    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended: false }));

    app.use(morgan('combined'))
    app.use(cors({
        credentials: true
    }))
});
app.use(cors({
    credentials: true
}))

const mongodb_conn_module = require('./mongodbConnModule');
var db = mongodb_conn_module.connect();


}));

以上是关于Node.js - Express会话数据不会持久化的主要内容,如果未能解决你的问题,请参考以下文章

node.js + express.js:使用 mongodb/mongoose 处理会话

Node.js - 会话不会通过 res.redirect() 持续存在

没有 req.session.save() 会话不会保存在 Node.js 中

会话如何在 Express.js 和 Node.js 中工作?

Node.js 和 Express 会话处理 - 后退按钮问题

Node.js_express_临时会话对象 npm install express-session