【发布时间】:2019-04-02 13:41:22
【问题描述】:
我正在像这样使用body-parser 包:
// For parsing application/json:
app.use(require('body-parser').json());
// For parsing application/x-www-form-urlencoded
app.use(require('body-parser').urlencoded({ extended: true }));
当收到像{ "foo": "bar" } 这样的有效输入时,一切正常,我可以使用req.body 访问已解析的对象。
但是,当发送无效(非 JSON)数据时:
data: JSON.stringify("just something inappropriate"),
我收到此错误:
{ SyntaxError: Unexpected token " in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError
at ...
expose: true,
statusCode: 400,
status: 400,
body: '"Something"',
type: 'entity.parse.failed' }
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ...
如何正确处理以防止服务器关闭?
【问题讨论】:
-
尝试阅读 expressjs 错误处理:expressjs.com/en/guide/error-handling.html,可能你需要有默认的错误处理程序。
标签: javascript node.js express error-handling body-parser