【问题标题】:NodeJS, express: validating request json payload on server to check JSON is not corruptNodeJS,express:验证服务器上的请求 json 有效负载以检查 JSON 是否损坏
【发布时间】:2017-06-01 07:23:24
【问题描述】:

我正在尝试开发一种服务来处理客户端在 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 数据缺少冒号 (:) 的请求时出现的错误

任何帮助表示赞赏!谢谢

【问题讨论】:

  • “尝试使用 try catch 进行错误处理,但这似乎不起作用”——我在您提供的代码中的任何地方都看不到这种尝试。
  • @Quentin 我现在已经删除了 try catch,但之前我已经在 "app.use(bodyParser.json());" 周围放置了 try和“var jsonObj = request.body;”在几个论坛上阅读后不起作用,我认为这是因为异步代码,但不确定。

标签: javascript json node.js express post


【解决方案1】:

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

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):
});

【讨论】:

  • 您好,感谢您的回复!但是我怎样才能在 app.post() 方法中使用这个结构呢?
  • 据我了解,您的错误甚至在请求到达 POST 路由之前就发生了。如果您将错误处理中间件添加到代码中,则当您的请求/响应链中出现任何错误时,错误将通过它。在此处阅读有关错误中间件的更多信息expressjs.com/en/guide/error-handling.html
  • 我也在考虑关于发布之前发生的错误的同样事情,但无法弄清楚错误处理代码的放置位置。现在想通了。感谢您的帮助!
猜你喜欢
  • 2017-10-17
  • 2013-09-24
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多