Salitha
Salitha

Reputation: 1147

express return erros as JSON instead HTML

I'm developing simple api with ExpressJS and when an error generated in express (out of my control, ex: express-jwt middleware or some 404 error etc.), it returns a html response. Tried changing request headers in postman but same. I tried body-parser and setting content-type header in middleware also.

But all responses I send with res.send() works normally.

This is a 404 error I got.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">>Error</title>
    </head><body><pre>Cannot GET /test</pre></body>
</html>

Is there a way to set response type globally to the app? Or is this because something I do wrong in postman?

Upvotes: 0

Views: 1092

Answers (1)

Shrey Gupta
Shrey Gupta

Reputation: 392

Use can add a error handler after adding all the routes .

app.use(function(err, req, res, next) {
  console.error(err.message); // Log error message in our server's console
  if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
  res.status(err.statusCode).send({error : err.message}); // All HTTP requests must have a response, so let's send back an error with its status

Upvotes: 1

Related Questions