在 Express 中捕获非法 JSON POST 数据?
当使用有效的 JSON 创建 POST 请求时,bodyParser 会正确解析 POST 请求的正文。但是,如果我提交无效的 JSON 字符串作为正文,则会收到错误:
SyntaxError: Unexpected token ILLEGAL
at parse (native)
at IncomingMessage.<anonymous>(/home/.../middleware/bodyParser.js:69:15)
...
因此,正文解析器在解析正文期间似乎失败。但是,我想捕获此失败并返回错误。我不确定我能做些什么来抓住它,所以任何帮助将不胜感激。谢谢。
When creating a POST request with valid JSON, the bodyParser parses the body of the POST request correctly. However, if I submit an invalid JSON string as the body, I receive the error:
SyntaxError: Unexpected token ILLEGAL
at parse (native)
at IncomingMessage.<anonymous>(/home/.../middleware/bodyParser.js:69:15)
...
So, it appears that the body parser is failing during the parsing of the body. However, I would like to catch this failure and return an error. I'm unsure what I can do to catch it, so any help would be appreciated. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它位于 connect.js bodyParser 中间件中。它确实执行了 try/catch,然后调用 next(err)。您应该能够捕获此错误并使用
app.error()
回调挂钩使用其他自定义代码进行处理。 http://expressjs.com/guide.html#error-handlingThis is in the connect.js bodyParser middleware. It DOES do a try/catch and then calls next(err). You should be able to catch this error and handle with additional custom code using the
app.error()
callback hook. http://expressjs.com/guide.html#error-handling由于某种原因,当使用express/connect时,JSON.parse不会抛出异常,这就是错误处理程序不触发的原因。
我已经记录了express的问题以了解发生了什么,但与此同时你可以使用这个解决方法:
更新:express的作者不熟悉这个问题,所以我想知道是否是另一个库导致它。必须一点一点地拆解我的代码才能找出这种行为是在哪里引入的。
For some reason, when using express/connect, JSON.parse doesn't throw exceptions, which is why your error handler doesn't fire.
I've logged an issue with express to find out what's going on, but in the meantime you can use this workaround:
update: this issue is not familiar to the author of express, so I am wondering if it's another library causing it. Will have to dismantle my code piece by piece to figure out where this behaviour is being introduced.
尝试将您的
app.use(express.bodyParser());
后
app.use(express.errorHandler(...))
为我解决了这个问题。
您还可以调整以下代码来管理错误
Try to put your
app.use(express.bodyParser());
after
app.use(express.errorHandler(...))
solved it for me.
You may also adapt the following code to manage the error
bodyParser 必须位于 app.use(app.router) 之上,错误处理程序的相对位置与 Perki 无关
bodyParser must be above app.use(app.router), it doesn't matter relative location to error handler as Perki