How do I get a node.js server to redirect users to a 404.html page when they enter an invalid url?
I did some searching, and it looks like most results are for Express, but I want to write my server in pure node.js.
session. user = o; res. redirect('/home'); } else{ res. render('/login', { title: 'Hello - Please Login To Your Account' }); } }); } });
The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below. const app = require('express')(); // The `res.
The logic of determining a "wrong" url is specific to your application. It could be a simple file not found error or something else if you are doing a RESTful app. Once you've figured that out, sending a redirect is as simple as:
response.writeHead(302, {
'Location': 'your/404/path.html'
//add other headers here...
});
response.end();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With