Accept Only JSON Content Type In A Post or Put Request In ExpressJS
<p>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.</p>

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

<pre><code>app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
</code></pre>

<p>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 <code>400 Bad Request</code>. </p>

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

<p>My last error handler middleware:</p>

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

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