How to redirect 404 errors to a page in node js server?
How to Redirect 404 Errors to a Page in Node.js Server
To redirect 404 errors to a page in a Node.js server, you can follow these steps:
Create a middleware function that will handle the 404 errors and redirect them to the desired page. This middleware function will be executed when no other routes or middleware match the requested URL.
Define the middleware function with the following parameters:
req
,res
, andnext
. Thereq
parameter represents the request object, theres
parameter represents the response object, and thenext
parameter is a callback function that passes control to the next middleware function.Inside the middleware function, use the
res.redirect()
method to redirect the request to the desired page. Pass the URL of the page as an argument to theres.redirect()
method.Set the status code of the response to 404 using the
res.status()
method. This will ensure that the response has the appropriate status code for a 404 error.Call the
next()
function to pass control to the next middleware function in the stack.
Here's an example of how the code might look:
app.use(function(req, res, next) {
res.status(404).redirect('/error-page');
});
In this example, the middleware function is defined using app.use()
, which means it will be executed for all requests. You can also specify a specific route or routes where this middleware should be applied.
The res.redirect('/error-page')
method redirects the request to the /error-page
URL. You can replace /error-page
with the desired URL of the page you want to redirect to.
The res.status(404)
method sets the status code of the response to 404.
Finally, the next()
function is called to pass control to the next middleware function.
Please note that this is a basic example, and you may need to customize it based on your specific requirements and the framework or library you are using for your Node.js server.