Accept only JSON content type in message or request in ExpressJS

I am working with Framework ExpressJS to create a REST API. All APIs should accept only the JSON request body for the POST, PUT, and PATCH request methods.

I am using the express.bodyParser module to parse the JSON body. It works great.

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

If there is a syntax error in my JSON body, my last error handler middleware gets called fine and I can configure the answer as 400 Bad Request.

But if I pass the content type to nothing, and not application/json, like (text/plain,text/xml,application/xml), the body parser module analyzes it without errors, and in this case the error handler middleware will not be called.

My latest 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-handling tool in case the content type is not applicaition/json.

+4
source share
1 answer

To do this, you just need to use the option typefrom bodyparser.jsonthe configuration options

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

Alternative wildcard can be used

app.use(bodyParser.json({
    type: "*/*"
}));
+5
source

All Articles