gpt4 book ai didi

node.js - NodeJS语法错误: Unexpected string in JSON at position 16

转载 作者:太空宇宙 更新时间:2023-11-03 22:59:35 26 4
gpt4 key购买 nike

我正在使用 body-parser 中间件来处理 REST API 中的 JSON 请求正文。

我尝试“破解”并测试系统如何处理此类输入:

// Note the "form": "a" does not include the required ","
{
"from": "a"
"destination": "Netanya",
"date": {
"start": "15-07-2018"
}
}

现在我不知道在哪里可以捕获这样的输入语法错误的错误。

我尝试删除 body-parser 并且没有抛出错误,但是当然,我无法在 req.body 中获取数据。

最佳答案

如上所述here并测试了以下代码:

app.use(bodyParser.json());

app.use(function (error, req, res, next) {
if(error instanceof SyntaxError){ //Handle SyntaxError here.
return res.status(500).send({data : "Invalid data"});
} else {
next();
}
});

更新=========

有六种类型的错误:

  1. EvalError:以不正确的方式使用 eval() 函数时引发。
  2. RangeError:当数值变量超出其允许的范围时引发。
  3. ReferenceError:使用无效引用时引发。
  4. SyntaxError:解析 JavaScript 代码时发生语法错误时引发。
  5. TypeError:当变量的类型不符合预期时引发。
  6. URIError:以不正确的方式使用encodeURI() 或decodeURI() 函数时引发。

关于node.js - NodeJS语法错误: Unexpected string in JSON at position 16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51628883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com