我尝试使用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我尝试传递给服务器无效,我的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传递是否无效并使用json消息400
返回{ "someerror":"somemessage"}
答案 0 :(得分:3)
在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);