Home > database >  Express middleware for empty post request body
Express middleware for empty post request body

Time:09-27

Is there any middleware to apply for controller when post request is triggered without payload (empty body)? Instead of defining on every post request, and checking has it body or not, would be awesome to have some sort of middleware to apply that automatically catches empty body and sends back 400 error for user with default json message. :)

CodePudding user response:

This is quite easy to make yourself:

app.use((req, res, next) => {
  if (Object.keys(req.body || {}).length === 0) {
    return res.status(400).json({ message : 'no payload' });
  }
  return next();
});

Or use a more elaborate validation suite like joi-express.

CodePudding user response:

If you only need to validate empty payload use below middleware function

var requestPayloadEmpty = (req, res, next) =>{
    if (Object.prototype.toString.call(value) === '[object Object]' && JSON.stringify(value) === '{}') {
        return res.status(400).json({ message : 'No payload' });
    }
    return next();    
}
    
app.use(requestPayloadEmpty)
    

If you need more validation than this use express-validator or joi package to validate other stuff

  • Related