捕获 express.json() 中间件抛出的错误 json 格式的错误

Suj*_*ari 8 node.js express

SyntaxError: Unexpected string in JSON at position 59当 json 数据的格式无效时,我收到html 格式的错误。我不知道为什么它给我 html 而不是错误对象。
我已经设置了我的标题如下。


//header middlewares
app.use((req, res, next) => {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
  });
Run Code Online (Sandbox Code Playgroud)

我想捕获错误并以以下格式发送消息。

{ 
  "status":404,
  "message":Unexpected string in JSON at position 59
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>SyntaxError: Unexpected string in JSON at position 59<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at parse (C:\Users\mydirectory\auth\node_modules\body-parser\lib\types\json.js: 89: 19)<br> &nbsp; &nbsp;at C:\Users\mydirectory\auth\node_modules\body-parser\lib\read.js: 121: 18<br> &nbsp; &nbsp;at invokeCallback (C:\Users\mydirectory\auth\node_modules\raw-body\index.js: 224: 16)<br> &nbsp; &nbsp;at done (C:\Users\my-directory\auth\node_modules\raw-body\index.js: 213: 7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (C:\Users\mydirectory\auth\node_modules\raw-body\index.js: 273: 7)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js: 203: 15)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js: 1145: 12)<br> &nbsp; &nbsp;at process._tickCallback (internal/process/next_tick.js: 63: 19)</pre>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)


我试着捕捉这个错误。

app.use((err, req, res, next) => {
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        console.error(err);
        return res.status(400).send(err); // Bad request
    }
    next();
});
Run Code Online (Sandbox Code Playgroud)


但我现在得到的回应如下。

{
    "expose": true,
    "statusCode": 400,
    "status": 400,
    "body": "{\n\t\"username\":\n}",
    "type": "entity.parse.failed"
}
Run Code Online (Sandbox Code Playgroud)

Suj*_*ari 10

我在 expressjs github repo 上发布了这个问题,我得到了一个很好且合理的解决方案。

如果你想要那个特定的响应,那就是你需要在错误处理程序中发送的内容,而不是 err 对象本身。

 app.use((err, req, res, next) => {
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        console.error(err);
        return res.status(400).send({ status: 404, message: err.message }); // Bad request
    }
    next();
});
Run Code Online (Sandbox Code Playgroud)

现在我可以发送所需的响应。

{
   "status": 404,
   "message": "Unexpected string in JSON at position 37"
}
Run Code Online (Sandbox Code Playgroud)

问题链接

  • 谢谢你!很有帮助。这是一个重要的安全问题,因为它会暴露您的目录结构。 (2认同)