【问题标题】:body-parser catch bad JSONbody-parser 捕获错误的 JSON
【发布时间】:2020-03-31 23:56:40
【问题描述】:

是否有可能在 body-parser 中发现错误的 JSON 语法?

以下代码显示了我的尝试。问题是我在收到回复时无法访问任何err.status

SyntaxError: Unexpected token ] in JSON at position 57...

这是作为 HTML 页面提供给调用者的。我宁愿抓住那个错误并格式化一个漂亮的 JSON 作为响应。

代码尝试:

class ExampleServer extends Server {
    constructor() {

        ...

        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({extended: true}));
        this.app.use((err) => {
            if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
                Logger.Err('Bad JSON.');
            }
        });

        ...
    }
}

我通过 POST 正文发送的损坏的 JSON:

{
    "numberValue": 6,
    "requiredValue": "some string here"]
}

我使用的body-parserexpress的版本:

"body-parser": "^1.19.0",
"express": "^4.17.1",

如何捕获损坏的 JSON 错误?

【问题讨论】:

    标签: node.js json express error-handling body-parser


    【解决方案1】:

    是的,可以指示 Express 捕获错误的 JSON 语法。尝试修改此代码:

    this.app.use((error: any, req: any, res: any, next: any) => {
      if (error instanceof SyntaxError) {
        // Catch bad JSON.
        res.sendStatus(400);
      } else {
        next();
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多