New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bodyParser.json() doesn't support custom type option #247

Closed
hh54188 opened this Issue Jun 7, 2017 · 2 comments

Comments

Projects
None yet
2 participants
@hh54188

hh54188 commented Jun 7, 2017

Here is my script post request handler part:

const bodyParser = require('body-parser')

app.use( bodyParser.json({ type: 'secret' }) );       // to support JSON-encoded bodies
app.use( bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}) ); 

app.post('/upload', function (req, res) {
    console.log(req.get('Content-Type'));
    console.log(req.body);
});

The post request from client set a custom Content-Type which is secret. Then I want the server resolve the post data as json. So I set type parameter to secret.

However, in the post handler function, I can print the Content-Type value in header is secret, but the req.body result is empty. It seems the bodyParser doesn't resolve the request.

If I change the request Content-Type to default application/json and without setting the type parameter, everything would be all right.

Is there anything wrong with my code ?

@dougwilson

This comment has been minimized.

Member

dougwilson commented Jun 7, 2017

Hi @hh54188 for the type option:

This option can be a function or a string. If a string, 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.

So since you are providing a string that does not have a / (all valid content-type values require a slash -- see the HTTP specification), then since there is no normal reason this would represent the content-type value, instead it is defined to be the file extension, i.e. it is looking for a body that would result in a .secret file name.

If you want to match against an invalid content-type value, that is fine, but you just need to use the function form of the type option:

app.use( bodyParser.json({ type: (req) => req.get('Content-Type') === 'secret' }) ); // to support JSON-encoded bodies

@dougwilson dougwilson closed this Jun 7, 2017

@dougwilson dougwilson self-assigned this Jun 7, 2017

@dougwilson dougwilson added the question label Jun 7, 2017

@hh54188

This comment has been minimized.

hh54188 commented Jun 7, 2017

Thank you for your reply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment