如何使用 Express 或 Body-Parser 拒绝无效的 JSON 正文

Ave*_*579 5 json node.js express

我正在创建一个仅接受 json 主体类型并使用主体解析器和express 的应用程序。不断出现的问题是,如果我发送无效的 json 正文,那么我的程序将向用户和控制台抛出一个愚蠢的错误。我如何防止此控制台错误并拒绝具有不正确 JSON 正文的请求。

预先感谢,艾弗里。

附言。这是一些示例代码来展示我正在做的事情:

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

app.use(bodyParser.json());

app.post('/test', function(req, res){
   res.status(200).send("Hi");
});

app.listen(8081, function(){
   console.log("Server is running");
});
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 8

您需要将一些错误处理中间件附加到您的应用程序。如何处理该错误取决于您,但作为如何执行此操作的示例:

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

app.use(bodyParser.json());

// this is a trivial implementation
app.use((err, req, res, next) => {
  // you can error out to stderr still, or not; your choice
  console.error(err); 

  // body-parser will set this to 400 if the json is in error
  if(err.status === 400)
    return res.status(err.status).send('Dude, you messed up the JSON');

  return next(err); // if it's not a 400, let the default error handling do it. 
});

app.post('/test', function(req, res){
   res.status(200).send("Hi");
});

app.listen(8081, function(){
   console.log("Server is running");
});
Run Code Online (Sandbox Code Playgroud)