pbattisson
pbattisson

Reputation: 1240

Express parse JSON without content-type header

I have an Express API which is replacing an existing API. The existing API receives JSON data but does not require the content-type header. Express seems to require this header for any parsing of the body into JSON and is returning undefined.

Is there a way to get Express to assume the data is a JSON type without the content-type header set?

Upvotes: 3

Views: 2312

Answers (1)

Rain336
Rain336

Reputation: 1498

The parseing of request bodies is done using the body-parser library which has an option to change the allowed content-type header values. Here an example that replaces the check with a function that always returns true, thereby always trying to parse the body as json.

const bodyParser = require('body-parser');

app.use(bodyParser.json({
  type(req) {
    return true;
  }
}))

Upvotes: 12

Related Questions