Express-Session MongoDB会话不持久

时间:2019-10-09 07:34:25

标签: node.js mongodb express session cookies

我是新手,这是我的第一个严肃的编码项目。我已经尝试了100万件事,但我不知道为什么会议没有通过不同的途径持续进行。当我从两条路径登录req.session.id时,当我应该使用相同的ID时会给我两个不同的ID。

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const session = require('express-session');
const bcrypt = require('bcrypt');
let User = require('./models/user.model');
const MongoStore = require('connect-mongo')(session);

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.set('trustproxy', true);

app.use(cors(corsOptions));
app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
    console.log("MongoDB database connection established successfully")
})

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

const SESS_NAME = 'session';
const SESS_SECRET = 'youshouldchangethis'
const IN_PROD = false;

app.use(session({
  name: SESS_NAME,
  resave: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection }),
  saveUninitialized: true,
  secret: SESS_SECRET,
  proxy: true,
  cookie: {
      sameSite: true,
      secure: IN_PROD,
  }
}));

登录路由会创建会话(此时将会话存储在Mongodb中就可以了),然后将重定向重定向到仪表板,其中req.session返回未定义,并且我无法访问该会话。这是登录和仪表板路线。任何帮助将不胜感激!

app.post('/login', (req, res) => {
  console.log("in login post");
  User.findOne({ email: req.body.email })
    .then(user => {
      bcrypt.compare(req.body.password, user.password, function (err, result) {
        if(result == true){
          req.session.userId = user._id;
          console.log(req.session.id);
          res.send(user);
        } else {
          res.send('Authentication Failed');
        }
      })
    })
    .catch(err => res.send('Authentication Failed'));
});

// Dashboard Router
app.get('/dashboard', (req, res) => {
  if (req.session.userId){
    User.findOne({ email: req.session.user.email }) // FIX: not able to find session / user
      .then(user => {
        console.log("found user")
        // req.session.user = user;
        res.send(user);
      })
      .catch(err => {
        //req.session.reset();
        res.send(err);
      })
  } else {
    console.log(req.session.id);
  }
});

1 个答案:

答案 0 :(得分:0)

我在express-session文档中找到了这个,也许这就是您要寻找的:

  

Session.save(回调)

     

...   在某些情况下,调用此方法很有用,例如,重定向,长期存在的请求或在WebSocket中。

req.session.save(function(err) {
  // session saved
})