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.
source
share