NodeJS,express:在服务器上验证请求json有效负载以检查JSON是否已损坏

时间:2017-01-17 09:38:34

标签: javascript json node.js express post

我正在尝试开发一个服务来处理客户端在POST请求中发送的一些JSON数据。我已经开发了服务和功能,如果POST请求中的JSON数据没有错误,但是如果请求中的json数据损坏(缺少大括号或逗号),那么服务就会中断。我是node的新手,尝试使用try catch进行错误处理,但这似乎不起作用。有人可以看看这段代码和错误,并帮我弄清楚如何在node.js中正确处理错误

server.js

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());

app.post('/', function(request, response){

response.set("Content-Type", "application/json");
var jsonObj = request.body;
var responseJson = {};
if(jsonObj.hasOwnProperty("payload"))
{
var keyResponse = "response";
responseJson[keyResponse] = "Here is processed data";
response.status(200);
}
else
{
    response.status(400);
    var keyResponse = "error";
    responseJson[keyResponse] = "JSON parsing failed";
}
response.send(responseJson);
})
var port = process.env.PORT || 3000;
app.listen(port);
console.log("Sever is up and listening on port "+port);

错误:

SyntaxError: Unexpected token p in JSON at position 6
at JSON.parse (<anonymous>)
at parse (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/body-parser/lib/types/json.js:88:17)
at /Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/raw-body/index.js:262:16)
at done (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/raw-body/index.js:251:7)
at IncomingMessage.onEnd (/Users/Vov/Desktop/NineEntertainmentService/nine-service/node_modules/raw-body/index.js:307:7)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)

当我使用JSON数据缺少冒号(:)

的请求时,这是一个错误

任何帮助表示赞赏!感谢

1 个答案:

答案 0 :(得分:0)

您可以添加错误处理中间件来响应该特定错误。

Difficult to determine that an error is the result of bad JSON

app.use(function(err, req, res, next) {
  if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
    // Handle the error here
    console.error('Bad JSON');
    res.status(500).send('JSON parse error');
  }
  
  // Pass the error to the next middleware if it wasn't a JSON parse error
  next(err):
});