![]() |
When building APIs with Express.js, you might encounter a situation where instead of returning a JSON error message, your server returns an HTML error page. This can be frustrating, especially when your application relies on consistent JSON responses. In this article, we’ll explore why this happens and how to ensure that Express.js returns a JSON error message instead of an HTML error page. Why Express Returns HTML Error PagesExpress.js, by default, provides error-handling middleware that may serve HTML pages for errors, especially in development mode. This behavior is generally useful for web applications where the developer needs to see a detailed error page, but it is not ideal for APIs that need to return structured JSON error messages to clients. Common Causes
Approaches to solve the HTML Error Page in Express Server Table of Content Example: Express generates a server automatic HTML page.
In the above code, we have defined two routes (/ route) for the home page and (/about route) for the about page. But we haven’t defined a route /signin for the signin link in the navigation bar. So our page functions like this: Output: ![]() Express returning HTML-based error page So Here we can see as we have not defined any route for /signin, So when the user tries to send a request to /signin route, Express returns a server automatic HTML page. So we somehow need to stop it and give our own JSON error message. SolutionThe solution is pretty simple. We can fix it by adding a Middleware Function which is there in Express which can give us the desired result. Using Middleware FunctionsIt gets triggered when the server receives the request and before the response is sent to the client. So there are different purposes for using middleware functions like making API calls, getting some data from the database, Error Handling, etc. Here we need middleware to handle our error which will come when we will send a request to /signin route. So what we need to do is just we have to update our app.js by adding a middleware function that gets triggered when no route matches. It gives a JSON error message(i.e. page not found) instead of an HTML Page. Example: Implementation to show the use of middleware function.
Output: In this way, we are able to return the user a JSON error message instead of a server-generated HTML Page. This comes in handy when we want to deal with the error and want to send a JSON Format to the user. Explicitly Handle Errors in RoutesTo prevent unhandled errors from reaching the default error handler, you should handle errors explicitly within your route handlers. Use app.get('/some-route', async (req, res, next) => { Set |
Reffered: https://www.geeksforgeeks.org
Node.js |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |