Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 711
Manish Jangir Avatar asked Jun 05 '16 08:06

Manish Jangir


People also ask

Does Express automatically parse JSON?

Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.

What does JSON () do in Express?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

What is POST () in Express?

js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.

Which method is used to send the content in ExpressJS?

send() Function. The res. send() function basically sends the HTTP response. The body parameter can be a String or a Buffer object or an object or an Array.


1 Answers

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: "*/*"
}));
like image 62
gevorg Avatar answered Oct 07 '22 12:10

gevorg