13

I am building an API server using ExpressJS. I want to ensure that the server always responds with JSON data rather than HTML data. For all the custom routes that I define, I can make the server respond with JSON data.

But in case of errors like "Page not found (404)" or "Internal Server Error (500)" the server responds with HTML content. Is there any inbuild configuration settings that allow making these responses in JSON format?

I can define custom error handlers for this, but I wish to use the features of inbuild error handler like hiding stack trace based on NODE_ENV.

1 Answer 1

11

According to the express documentation, you may handle each 404 and 500 server errors like this to send json (or any other response you like)

Send 404 as a json reponse,

app.get('*', function(req, res){
    res.status(404).json({}); // <== YOUR JSON DATA HERE
});

For 500 Internal server error ,

app.use(function (err, req, res, next) {
    console.error(err.stack)
    res.status(500).json({}) // <== YOUR JSON DATA HERE
})

Hope that helps!

Please follow these references for more info

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. As mentioned in the question, I can define custom error handlers for returning the JSON response. However, I wish to use the features of inbuild error handler like hiding stack trace based on NODE_ENV.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.