How to validate json body in nodejs

Posted By : Md Imroz Alam | 07-Aug-2016

Validate JSON Body in Node.JS

If any api have wrong body of json passed.

To validate json body globally any api of application server. 

For example-> login api have required body to be below format, but by mistake body have "," left.


 

"email":"[email protected]",  // suppose, body have  , is not added, then throw error message:- wrong body of json 

Following code are useful in node.js


 
var express=require('express');
var bodyParser=require('body-parser');
var app=express();
app.use(bodyParser.json());

app.use(function(err,req,res,callback){

    if(err instanceof SyntaxError && err.status===400 && 'body' in err){

         res.status(403).send({

             "error":false,

             "message":"Wrong Body of json",

             "response":null

         })

          res.end()

    }

});

app.use(bodyParser());

 

I hope it will be helpful.

Thanks

About Author

Author Image
Md Imroz Alam

Md. Imroz Alam is a bright Web App Developer, he has good knowledge of Java, J2SE, Jsp, Servlet, jdbc. His hobbies are watching movie, playing carom.

Request for Proposal

Name is required

Comment is required

Sending message..