URL Redirection Using Node.js

Lets learn how to redirect with a 301 status code – which means “moved permanently”, using Node.js

Related Read: HTTP Server(request/response): Node.js

Here we’re passing 301 redirect status code with redirection location URL in the header information to the client – the browser.

JavaScript File
app.js

var http = require("http");

     http.createServer(function(req, res){
      res.writeHead(301, {
   "location" : "http://technotip.org"
  });
  res.end();
   }).listen(3030, "127.0.0.1");
 
 console.log("server redirects from localhost to technotip.org");

We require/include http module of node.js We call createServer() method of http object and this method passes 2 objects to the callback methodrequest and response objects. Using request object we call writeHead() method and pass 301 status code and the redirect location information. After this, we indicate the end of the process by calling end() method.

Also we assign the port 3030 at 127.0.0.1 for the client access of this server.

Now visit localhost:3030 or 127.0.0.1:300 and you’ll be redirected to http://technotip.org

301 Redirection Using Node.js



YouTube Link: https://www.youtube.com/watch?v=neIeFVMsuJY [Watch the Video In Full Screen.]



Status Code Definitions

Informational 1xx
100 Continue
101 Switching Protocols

Successful 2xx
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content

Redirection 3xx
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
306 (Unused)
307 Temporary Redirect

Client Error 4xx
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed

Server Error 5xx
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported