Search code examples
javascriptnode.jsexpressmongoosemiddleware

req.body undefined in custom middleware express


So I'm doing a simple NodeJS app with MongoDB/Express/Mongoose. In my mongoose schema I have a field (pictureURL) with a default value, the problem is that if pictureURL is an empty string the default value does not get applied. To solve this I though about using a custom middleware when doing the POST request either when creating or updating the model.

But the issue I'm having is that from within the middleware req.body is undefined. It is fine when in the router.post method but not in the middleware. Here is the code I have.

middleware (pictureU.js)

const app = require('../app');

const bookPictureUrl = (res, req, next) => {
  console.log({ body: req.body });
  if (!req.body.pictureUrl)
    req.body.pictureUrl = 'images/default';
  next();
};

module.exports = { bookPictureUrl };

book.routes.js

const app = require('../app');
    
const router = require('express').Router();
const Book = require('../models/Book.model');
const { bookPictureUrl } = require('../middleware/pictureUrl');

router.post('/update/:id', bookPictureUrl, async (req, res, next) => {
  try {
    req.body.authors = req.body.authors.split(',');
    const data = await Book.findByIdAndUpdate(req.params.id, req.body);
    res.redirect('/books');
  } catch (err) {
    next(err);
  }
});

Any help trying to fix this so that I can use req.body within the middleware would be greatly appreciate.

Thanks


Solution

  • You mixed up your argument order. req should come before res.

    const bookPictureUrl = (req, res, next) => {
      console.log({ body: req.body });
      if (!req.body.pictureUrl)
        req.body.pictureUrl = 'images/default';
      next();
    };