Search code examples
node.jsexpressmime-typescontent-typebody-parser

body-parser ignores type parameter


I have inbound requests with Content-Type: application/vnd.surveymonkey.response.v1+json. I'm trying to use body-parser on them. The documentation for body-parser's json factory method states:

Returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option.

[...]

The type option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime type with a wildcard (like / or */json). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/json.

I tried a variety of parameters, but regardless of whatever I put the parser middleware continues to accept application/json while rejecting application/vnd.surveymonkey.response.v1+json. In fact, when I put a console.debug statement in the type function, it never does print, so it looks like the type argument is being ignored entirely.

Am I doing anything wrong? what do I need to do for body-parser to respect the type parameter?

import * as bodyParser from 'body-parser';
import * as express from 'express';

const app = express();
app.use(
  bodyParser.json({
    // type: 'application/vnd.surveymonkey.response.v1+json', // doesn't work
    // type: ['application/vnd.surveymonkey.response.v1+json'], // doesn't work
    // type: ['application/*'], // doesn't work
    // type: (req) => /application\/(.+\+)?json/.test(req.headers['Content-Type'] as string), // doesn't work
    type: (req) => console.debug('Hello world!'),
  })
);

app.post(`/`, (req, res) => {
  console.log('Request: ', req.body);
  res.status(200).send();
});

Solution

  • It turns out that the problem was that I was running on Firebase Functions, which already runs body-parser on inbound requests. Adding another instance of body-parser is a no-op, which is why it was being ignored.