我正在尝试使用 NodeJs 编写简单的 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 无效,我的 Express 崩溃了,我对此无能为力。我抓不到它或任何东西。我怎样才能捕获这个错误?
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"}