expressjs / body-parser

Node.js body parsing middleware
MIT License
5.44k stars 727 forks source link

How to handle content-type mismatch? #498

Closed robahtou closed 1 year ago

robahtou commented 1 year ago

For example, I explicitly set the type in the JSON body-parser:

router.post('/the-right-content-type',
  (req, res, next) => {
    bodyParser.json({
      type: 'application/json'
    })(req, res, error => {
      console.log('here', error); // undefined      

     if (error instanceof SyntaxError) {
        res.sendStatus(400);
      } else {
        next();
      }
    });
  },
  (req, res, next) => {
    res.send('ok);
  }
);

Then I hit the API with curl:

 curl -v "localhost:4000/the-right-content-type" \
 -H "Content-Type: text/html" \
 -d 'cheese'

I expected an error to be thrown since the content-type does not match the JSON body-parser. But this isn't the case. The docs are not very clear on what to expect with type. Can someone help explain what to expect with setting type and when a request doesn't match the content-type?

Ideally I want to capture this with express error handler (if this is an error) or just be able to handle in express when there is a content-type mismatch.

dougwilson commented 1 year ago

Hello, and thank you for your question. The type is just a filter, so when it doesn't match, the parser will just not parse the request body. It does not error or anything. This is what the readme says about the expected behavior:

All middlewares will populate the req.body property with the parsed body when the Content-Type request header matches the type option, or an empty object ({}) if [...] the Content-Type was not matched [...].

I hope that helps! If you want to outright reject requests without a specific content-type, you'll want to add code for that in your handler 👍