jshttp / type-is

Infer the content-type of a request.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error thrown by media-typer when Content-Type header not set

thierer opened this issue · comments

I ran into an issue when using express 4.16.2 and body-parser.urlencoded to handle a POST request with an optional body.

When the body was empty, the request had Content-Length: 0 but no Content-Type header. That caused an error "TypeError: argument string is required" which was ultimately thrown by

https://github.com/jshttp/media-typer/blob/d49d41ffd0bb5a0655fa44a59df2ec0bfc835b16/index.js#L141

but I think the root cause is

type-is/index.js

Lines 139 to 142 in 9e88be8

// request content type
var value = req.headers['content-type']
return typeis(value, types)

(or any of the methods typeis() calls) because none of them check if the Content-Type header is set.

Now, the fix was easy (just set Content-Type even for an empty body) and it might well be that the specs require that for all POST requests anyway.

So the only reason I'm opening this issue is that I wonder if it's really the intended behaviour, as the comment for typeofrequest() states

* If there is no content type, `false` is returned.

which obviously isn't true, as media-typer.parse() throws before that can happen...

Yea, it should definately not throw, just return false. We have the no content type test https://github.com/jshttp/type-is/blob/master/test/test.js#L42-L49 but maybe the test is not working correctly? Is it possible you can put together a reproduction that only uses this module so we can see it? Alternatively you're welcome to make a PR 👍 Just made the code change and add a test that fails without the code change and passes with the code change.

I think the throw is triggered by the combination of Content-Length being set and Content-Type not being set, which the test might not cover (because if Content-Length is not set, typeofrequest() already bails early).

I'll come up with either a test case or a PR and get back to you.

Gotcha! 👍 I tried a few different things, following your description but still just getting the return value false and no thrown error. Not sure how to reproduce. I'll wait on one of your two things because I'm not sure how to fix it if I cannot reproduce. Also maybe also want to double check you're using the latest version of this module, in case we are using different versions and that's why I'm not seeing it.

Sorry for the noise. The error is actually caught, but I accidentally had "Break on all exceptions" enabled 🤦‍♂️.

Ah, gotcha. It's no problem at all.