未访问 Express 中间件

Express middleware isn't being accessed

下面的代码是用于创建 属性 req.user 的中间件,如果 req.session.user 存在,则包含用户 obj。然而,出于某种原因,它永远不会进入中间件。所以 'hihihhiihi' 也没有打印出来。

// have middleware that deserializes the logged in user
// if req.session.user exists, then create property req.user that contains the user obj
app.use(async (req, res, next) => {
  console.log('hihihhiihi');
  if(req.session.username) {
    console.log(req.session.username,' is abcdefg');
    req.user = await User.findOne({username: req.session.username}).exec();
  }
  next();
});

这是我的App.js

import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';

import diaryRoutes from './routes/diarys.js';
import userRoutes from './controllers/user.js'
const app = express();

// app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
import session from 'express-session';

// after login, don't have to enter username and pw again
// ...so sessions
const sessionOptions = { 
  secret: 'secret for signing session id', 
  saveUninitialized: false, 
  resave: false 
};

app.use(session(sessionOptions));

app.use((req, res, next) => {
  console.log('session contains', req.session);
  next();
});

// have middleware that deserializes the logged in user
// if req.session.user exists, then create property req.user that contains the user obj
app.use(async (req, res, next) => {
  console.log('hihihhiihi');
  if(req.session.username) {
    console.log(req.session.username,' is abcdefg');
    req.user = await User.findOne({username: req.session.username}).exec();
  }
  next();
});

app.use('/diarys', diaryRoutes);
app.use('/users', userRoutes);

const CONNECTION_URL = 'someurl';
const PORT = process.env.PORT || 5000;

mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => app.listen(PORT, () => console.log(`Server Running on Port ${PORT}`)))
  .catch((error) => console.log(`Error message(can't connect): ${error}`));

我意识到我在前端使用 React 并且我还使用 res.json() 将响应发送到前端,所以我应该使用

app.use(express.json());

而不是

app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))

如果有人遇到类似问题,请检查您使用的是 res.json 还是 res.render :)