I'm using the body-parser
package like this:
// 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 }));
When a valid input like { "foo": "bar" }
is received everything works fine and I can access the parsed object with req.body
.
However, when invalid (non-JSON) data is sent:
data: JSON.stringify("just something inappropriate"),
I get this error:
{ 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 ...
How can I handle this properly to prevent the server from shutting down?