node.js - 尝试 - 当 JSON 有反斜杠时,Catch 没有正确响应

标签 node.js

我有一个 router.post 如下

router.post('/newlead', async (payload, res, next) => {
...
...
...
});

Payload 以 JSON 对象的形式出现在正文上

{
    "name": "Danielle",
    "age": 26
}

当我发送这样的正文时:

{
    "name": "\Danielle",
    "age": 26
}

我得到了错误

SyntaxError: Unexpected token in JSON at position X.

我在 try{}catch{} 中尝试了 JSON.parse(payload.body),但我仍然收到错误,好像 try/catch 不会在那里。

POSTMAN 会发生这种情况,但 Angular 应用程序不会发生这种情况。

有没有办法识别此错误并向用户显示消息?

更新:代码太长无法发布,但这是行不通的:

const express = require('express');
const sql = require('mssql');
const router = express.Router();

router.post('/newlead', async (payload, res, next) => {
    try{
    let test=JSON.parse(payload.body)
    console.log("ok")
    }
    catch(err) {
    console.log(err)
    return;
    }
    res.json(payload.body)

});
module.exports = router;

这是我在 index.js 的中间件

//Middleware
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', '*');
    res.header("Access-Control-Allow-Headers", "accept, content-type");
    next();
})
app.use(express.json()); //to read bodies

最佳答案

您的 express.json() 中间件在解析客户端发送的无效 JSON 时遇到错误,框架正在提供默认错误处理响应。

要以自定义方式处理错误,请考虑像这样安装自定义错误处理中间件:

app.use(function (err, req, res, next) {
  if (err.type === 'entity.parse.failed') {
    // Your custom error handler here
    res.status(500).send('The client sent invalid JSON');
  } else {
    // Something else went wrong. Pass it along.
    next(err);
  }
})

重要:确保最后安装这个中间件,在所有其他 app.use 指令之后。

关于node.js - 尝试 - 当 JSON 有反斜杠时,Catch 没有正确响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68341013/

相关文章:

node.js - Mongoose 填充两个简单的模式

javascript - 使用 Promises 响应来自 Node.js 的请求

mysql - 在nodejs中使用现有的mysql模式

node.js - cerf 在本地主机中从 ssl 生成 HTTPS 时出现问题

node.js - npm start 不打开浏览器选项卡

javascript - 如何解析node js请求中的url参数

node.js - jsreport 简单报告 - 无输出

javascript - Node js 重用现有的 buff 调用

javascript - 显示具有下标(或上标)样式的菜单项标签

node.js - SSL/https 从 header 中删除 X-CSRFToken