req.session是未定义的nodeJS

时间:2018-11-08 21:53:01

标签: node.js express

我试图在NodeJS中建立一个会话,然后在我的/ auth路由中使用它,但是我在会话中遇到了不确定的麻烦。

在app.js中:

const express = require('express'),
  path = require('path'),
  bodyParser = require('body-parser'),
  cors = require('cors'),
  mongoose = require('mongoose'),
  config = require('./config/DB');

const app = express();
  const session = require('express-session')
  const MongoStore = require('connect-mongo')(session);

mongoose.connect(config.DB, { useNewUrlParser: true }).then(
  () => { console.log('Database is connected') },
  err => { console.log('Can not connect to the database' + err) },
  options
);
const db = mongoose.connection


const adUnitRoutes = require('./routes/adunit.route');
const userProfileRoutes = require('./routes/userprofile.route');


app.use('/adunits', adUnitRoutes);
app.use('/userprofile', userProfileRoutes);

app.use(session({
  secret: 'my-secret',
  resave: false,
  saveUninitialized: true,
  store: new MongoStore({ mongooseConnection: db })
}));

在路线中:

userProfileRoutes.route('/authentification').post((req, res) => {

  console.log('req session : ' + req.session.userId);
//here I got cant read property of userId because session is undefined

});

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为您在添加中间件之前设置了路由。您的处理程序实质上是中间件,因此,如果将它们添加到session之前,则您的会话尚未处理并添加到请求中。

设置中间件后添加路由将使其按预期工作。

请参见以下最小化示例:

const express = require('express');
const app = express();
const session = require('express-session');

app.get('/broken', (req, res) => {
  console.log('req session : ' + req.session.userId);
  res.write(String(req.session.userId));
  req.session.userId = 1;
  res.end();
});

app.use(
  session({
    secret: 'my-secret',
    resave: false,
    saveUninitialized: true
  })
);

app.get('/ok', (req, res) => {
  console.log('req session : ' + req.session.userId);
  res.write(String(req.session.userId));
  req.session.userId = 1;
  res.end();
});

app.listen(8089);