Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - Redirect url

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.

like image 345
Dzung Nguyen Avatar asked Oct 07 '22 08:10

Dzung Nguyen


People also ask

How do I redirect a login page in node JS?

session. user = o; res. redirect('/home'); } else{ res. render('/login', { title: 'Hello - Please Login To Your Account' }); } }); } });

How do I use RES redirects?

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.


1 Answers

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();
like image 159
Chetan S Avatar answered Oct 14 '22 12:10

Chetan S