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> at JSON.parse (<anonymous>)<br> at parse (C:\Users\mydirectory\auth\node_modules\body-parser\lib\types\json.js: 89: 19)<br> at C:\Users\mydirectory\auth\node_modules\body-parser\lib\read.js: 121: 18<br> at invokeCallback (C:\Users\mydirectory\auth\node_modules\raw-body\index.js: 224: 16)<br> at done (C:\Users\my-directory\auth\node_modules\raw-body\index.js: 213: 7)<br> at IncomingMessage.onEnd (C:\Users\mydirectory\auth\node_modules\raw-body\index.js: 273: 7)<br> at IncomingMessage.emit (events.js: 203: 15)<br> at endReadableNT (_stream_readable.js: 1145: 12)<br> 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)