添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

I am getting SyntaxError: Unexpected string in JSON at position 59 error in html format when format of json data is not valid. I don't know why it is giving me html instead of error object.
I have set my header like below.

//header middlewares
app.use((req, res, next) => {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader("Access-Control-Allow-Origin", "*");
    next();
  });

I want to catch the error and send a message in below format.

"status" : 404 , "message" : "Unexpected string in JSON at position 59"

Here is the error that I get.

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Error</title>
</head>
<pre>SyntaxError: Unexpected string in JSON at position 59<br> &nbsp; &nbsp;at JSON.parse (&lt;anonymous&gt;)<br> &nbsp; &nbsp;at parse (C:\Users\mydirectory\auth\node_modules\body-parser\lib\types\json.js: 89: 19)<br> &nbsp; &nbsp;at C:\Users\mydirectory\auth\node_modules\body-parser\lib\read.js: 121: 18<br> &nbsp; &nbsp;at invokeCallback (C:\Users\mydirectory\auth\node_modules\raw-body\index.js: 224: 16)<br> &nbsp; &nbsp;at done (C:\Users\my-directory\auth\node_modules\raw-body\index.js: 213: 7)<br> &nbsp; &nbsp;at IncomingMessage.onEnd (C:\Users\mydirectory\auth\node_modules\raw-body\index.js: 273: 7)<br> &nbsp; &nbsp;at IncomingMessage.emit (events.js: 203: 15)<br> &nbsp; &nbsp;at endReadableNT (_stream_readable.js: 1145: 12)<br> &nbsp; &nbsp;at process._tickCallback (internal/process/next_tick.js: 63: 19)</pre>
</body>
</html>

I tried catching this error.

app.use((err, req, res, next) => {
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        console.error(err);
        return res.status(400).send(err); // Bad request
    next();
});

But the response that I get now is like below.

"expose" : true , "statusCode" : 400 , "status" : 400 , "body" : "{\n\t\"username\":\n}" , "type" : "entity.parse.failed"

Hi @Lordofcodes sorry you are having trouble. If you want that specific response, that is what you need to send in your error handler instead of the err object itself. Example:

app.use((err, req, res, next) => {
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        console.error(err);
        return res.status(400).send({ status: 404, message: err.message }); // Bad request
    next();
});

Any idea why this wouldn't work in my case (see below)?

I've tried several different things but the payload never arrives at the client for some reason..

See also: full question on stackoverflow .

// Global Error Handler
app.use((err: any, req: express.Request, res: express.Response, next: NextFunction) => {
  if (res.headersSent) {
    return next(err);
  const status = err.status || 500;
  res.status(status);
  res.setHeader('Content-Type', 'application/json');
  if (!(err instanceof HTTPError)) {
    return res.json(new HTTPError(status, err.message || 'Internal Server Error'));
  } else {
    return res.json(err);
});