Accept Only JSON Content Type In A Post or Put Request In ExpressJS
Asked Answered
F

1

9

I'm working with ExpressJS framework to create REST APIs. All the APIs should accept only JSON request body for POST, PUT and PATCH type of request methods.

I'm using express.bodyParser module to parse JSON body. It works perfectly fine.

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

If there is any syntax error in my JSON body, my last error handler middleware is perfectly called and I can customize the response as 400 Bad Request.

But, if I pass the content type anything rather than application/json like (text/plain,text/xml,application/xml), the body parser module parses it without error and my error handler middleware is not called in this case.

My last error handler middleware:

export default function(error, request, response, next) {
  if(error.name == 'SyntaxError') {
    response.status(400);
    response.json({
      status: 400,
      message: "Bad Request!"
    });
  }
  next();
}

What I want to do is call my last error handler middle in case of the content type is not applicaition/json.

Fichu answered 5/6, 2016 at 8:57 Comment(1)
You just need to add proper config option to bodyParser.json, look my answer.Tseng
T
12

To do this you just need to you use type option from bodyparser.json configuration options

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

alternative could be using wildcard

app.use(bodyParser.json({
    type: "*/*"
}));
Tseng answered 5/6, 2016 at 10:50 Comment(1)
To clarify why this works. This basically tells the json bodyparser to attempt to parse "all the things" which will throw an error if it is not valid json.Ridgeling

© 2022 - 2024 — McMap. All rights reserved.