NodeJS body parser SyntaxError: Unexpected token in JSON | JSON.parse

NodeJS can't handle the invalid JSON body by default, if you put wrong JSON body raw JSON then you'll encounter following error.

SyntaxError: Unexpected token } in JSON at position 75<br> &nbsp; &nbsp;at JSON.parse 

To prevent the error we can use middleware to solve the issue for all APIs.

 app.use((err, req, res, next) => {
   // This check makes sure this is a JSON parsing issue, but it might be
   // coming from any middleware, not just body-parser:

   if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
       console.error(err);
       return res.status(400).json({status: false, error: 'Enter valid json body'}); // Bad request
   }

   next();
});

Post a Comment

0 Comments