How to validate json body in nodejs
Posted By : Md Imroz Alam | 07-Aug-2016
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.