如何捕获这个错误NodeJs / Express?

我正在尝试使用NodeJ编写简单的Web服务。 我打电话给Ajax如下:

$.ajax({ type: "POST", url: "http://localhost:3800", // this json below is invalid and I need to verify it on server side data: '"jhhjh":"ssss"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function(data){ console.log(data); }, failure: function(errMsg) { console.log(errMsg); } }); 

然后在服务器端我有这样的代码:

 var express = require("express"), app = express(), bodyParser = require('body-parser'); app.use(bodyParser()); app.all('/', function(req, res, next) { // set origin policy etc so cross-domain access wont be an issue res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // that is the line that gives me error message and cannot return anything back to client res.send("all good"); }); app.post('/', function(req, res) { }); app.listen(process.env.PORT || 3800); 

然而,正如json我想传递给服务器是无效的我的快车崩溃,我不能做任何事情。 我不能抓到它或任何东西。 我怎样才能抓住这个错误?

 Error: invalid json at parse (C:\xampp\htdocs\testing\node_modules\body-parser\index.js:60:15) at C:\xampp\htdocs\testing\node_modules\body-parser\index.js:156:18 at IncomingMessage.onEnd (C:\xampp\htdocs\testing\node_modules\body-parser\node_modules\raw-body\index.js:113:7) at IncomingMessage.g (events.js:180:16) at IncomingMessage.EventEmitter.emit (events.js:92:17) at _stream_readable.js:920:16 at process._tickCallback (node.js:415:13) 

我怎样才能抓住这个错误? 我需要的是检测如果json传递是无效的,并返回400与json消息{ "someerror":"somemessage"}

       

网上收集的解决方案 "如何捕获这个错误NodeJs / Express?"

试试这个在server.js中:

 var express = require("express"), app = express(), bodyParser = require('body-parser'); app.use(bodyParser()); app.use(function(err,req,res,next){ if(err){ console.log(err); } next(); }); app.all('/', function(req, res, next) { // set origin policy etc so cross-domain access wont be an issue res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); console.log(req.body); next(); }); app.post('/', function(req, res) { if(!Object.keys(req.body)) res.json('all good'); else res.json({ success: false, error: "json invalid" }, 400); }); app.listen(process.env.PORT || 3800);