Home > Software engineering >  body inside express middleware is empty
body inside express middleware is empty

Time:05-08

i'm receiving emails from mailgun so i set my endpoint as follow

app.post(
'http://www.example.com/mail',
async(req, res, next) => {
   // i want to check if email coming from mailgun
  // so i want to set if statement using the req.body['X-Mailgun-Coming']
  // which should be Yes
 // but i got empty body object
},
uploadHandler.any(),
comingEmails // but body in this function has the required data
)

as you can see i got empty body in the middle ware but in the main function, body has the required and i has access to this data

note ==> this only happens when email has attachment

CodePudding user response:

uploadHandler.any() has to be BEFORE where you check req.body because it is that middleware that actually reads the body of the request and populates req.body. So, you are trying to read req.body before the code runs that actually puts the value in it.

Here's how you would put it before you try to use req.body.

app.post(
    'http://www.example.com/mail',
    uploadHandler.any(),
    async(req, res, next) => {
       // i want to check if email coming from mailgun
       // so i want to set if statement using the req.body['X-Mailgun-Coming']
       // which should be Yes
       next();
    },
    comingEmails
);
  • Related