1
votes

I am in the middle of setting up a REST API that takes requests with a custom Content-Type, but I am having trouble parsing the body with the NPM package body-parser. I am running some tests with Mocha and Chai-HTTP and seding my request tests like this:

chai.request(server)
.post('/demo')
.set('Content-Type', 'application/vnd+companyName.v01+json')
.send({name: 'test'})
.end(function(err, res) {/* tests are here */});

In my express app's app.js, I am calling this middleware:

app.use(bodyParser.json({type: 'application/*+json'}));

When I make the type more general, like making it 'application/*', I can pass the request through with a 'application/json' Content-Type, but not my custom one. When I do this, my req.body is an empty object. If bodyParser was just completely not working, req.body would be undefined and not an empty object. By looking at the docs, I feel like my options on my bodyParser call are correct, but clearly not - any insight?

1
You're not describing what you mean by "trouble parsing the body". - robertklep
Sorry. I mean that once I get through my middleware and to my route, req.body is an empty object. - loganhuskins
Hmm yeah I can reproduce the issue. Let me check... - robertklep
Thanks, let me know if you need more info. - loganhuskins

1 Answers

1
votes

vnd+companyName.v01+json isn't a valid media type.

A valid media type should look like:

[ tree. ] subtype name [ +suffix ] [ ; parameters ]

The subtype name can't contain . or + characters, those are reserved for the (optional) tree and suffix, respectively (RFC6838).

So in your case, the mime type should look like this:

application/vnd.companyName-v01+json

However, it seems that there's an additional requirement imposed by body-parser (or rather, type-is, which is used to match content type), in that the subtype name needs to be lower case:

application/vnd.companyname-v01+json

Strangely, that requirement only applies for the body-parser configuration part, the client is allowed to use upper case in its requests.