Routing in Node.js

Manvi Chaddha
Last Updated: May 13, 2022

Introduction

Node.js is a runtime environment for executing JavaScript code and is often used to build backend services. The main advantage of using Node.js is that it is super fast and highly scalable; due to this, Node.js is used in a production environment by large product-based companies, including PayPal, Uber, Netflix.  Node.js has a unique advantage because millions of front-end developers that write JavaScript for the browser can now write the server-side code and the client-side code without the need to learn a completely different language.

An application made using Java + Spring was redesigned using Node.js in PayPal. The developers found that the application made using Node.js was twice as fast with fewer people, had 33% fewer lines of code, and 40% fewer files.

Routing in Node.js is one of the most important concept one needs to have a solid grip on when building scalable applications using Node.js. Don't worry if you don't know anything about Routing in Node.js; this blog will teach you how to perform Routing from scratch.

Introduction to Routing

Before moving on to the technical jargon, let's take a look at an example. Suppose you visit any website generally there is a navigation bar at the top wherein you can find the link of different web pages of the main website. Each element of the Navigation bar contains links to different web pages. So if you click on one of those links, you will get redirected to that page.

Whenever a client enters the URL of the website in the browser, an HTTP request is generated, and in return, an HTTP Response is generated and the web page or the website is rendered to the client. These HTTP requests are sent to the backend server, which then responds to the request.The point to note is how the server will know which page is to be rendered corresponding to each request. 

Here Routing comes to Picture, Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). In simple terms, Routing allows targeting different routes or different URLs on our page.

Implementation of Routing in Node.js

There are mainly two ways to implement Routing in Node.js

  • By Using Framework
  • Without Using Framework.

We will cover Routing with and without framework in the following sections.

Routing Without Framework

Let’s take an example wherein there is a simple server setup using Node.js in the following app.js file.

// Node.js has a built-in module called HTTP,
// which allows Node.js to transfer data over the
//  HyperText Transfer Protocol (HTTP).
// To include the HTTP module, the require method is
// used
var http = require('http');

// The HTTP module can create an HTTP server that
// listens to server ports and gives a response back to the client.
// Use the createServer() method to create an HTTP server:
var server = http.createServer(function(req, res)
{
  // The function passed into the http.createServer()
  // has a req argument that represents the request from
  // the client, as an object (http.IncomingMessage object).
  // This object has a property called "url" which holds the
  // part of the url that comes after the domain name:
  console.log('A request was made: ' + req.url)

  // The first argument of the res.writeHead()
  // method is the status code, 200 means that
  // all is OK, the second argument is an object
  // containing the response headers.
  res.writeHead(200, {'Content-Type': 'text-plain'});
  res.end('Response ended'); // ends the response
});

server.listen(3000, '127.0.0.1');
console.log('Listening to port 3000')

Let’s run this file using the command node app.js in the terminal.

Let's append /api to the URL. The same page will be rendered again however a different HTTP Request is being made to render the /API page as can be seen in the screenshot below. 

You may literally append anything and the same page will be rendered again and different HTTP Requests will be generated for each.

This is not a desirable situation in real-world situations, and you want a different web page corresponding to each HTTP request. In the simple server setup code above, we saw a URL property corresponding to each request that is logged to the console every time a new request is generated. Therefore the URL property can be used to distinguish between multiple requests.

Now let's implement routing in the above example; if the requested URL is /home or /, then the index.html file needs to be rendered, The index.html contains an h1 tag only. The below code implements it.

app.js

var http = require("http");
var fs = require("fs");
var server = http.createServer(function (req, res) {
  console.log("A request was made: " + req.url);
  if (req.url === "/home" || req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    // The function fs.createReadStream() allows you to open up a
    // readable stream in a very simple manner. All you have to do
    // pass the path of the file to start streaming in. It turns
    //  out that the response (as well as the request) objects are
    // streams. So we will use this fact to create a http server
    // that streams the files to the client.
    fs.createReadStream(__dirname + "/index.html").pipe(res);

  }
});

server.listen(3000, "127.0.0.1");
console.log("Listening to port 3000");

Index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title></title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <h1>Coding Ninjas</h1>
  </body>
</html>

Now run the app using the command node app.js in the terminal. After the browser opens up on localhost:3000, append /home and / in turn.  You will notice that two new HTTP requests will be generated each for /home and/and the content of the index.html file will be displayed.

So we have just implemented basic Routing,

Now lets implement routing such that a different HTML file is displayed when the client appends /contact, /home, /social and a JSON objects when nothing is being appended. The app.js file will be implemented in the following manner.

var http = require("http");
var fs = require("fs");
var server = http.createServer(function (req, res) {
  console.log("A request was made: " + req.url);
  if (req.url === "/home" || req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    fs.createReadStream(__dirname + "/index.html").pipe(res);
  } else if (req.url === "/contact") {
    res.writeHead(200, { "Content-Type": "text/html" });
    fs.createReadStream(__dirname + "/contact.html").pipe(res);
  } else if (req.url === "/social") {
    res.writeHead(200, { "Content-Type": "text/html" });
    fs.createReadStream(__dirname + "/social.html").pipe(res);
  } else {
    var ninjas = [
      { name: "abc", age: 30 },
      { name: "def", age: 32 },
    ];
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(ninjas));
  }
});

server.listen(3000, "127.0.0.1");
console.log("Listening to port 3000");

Each of the html files contains an h1 tag and some text inside it. Run the app.js file and append /home, /contact and /social one by one. You will notice that different web page corresponding to each HTTP Request will be generated.

Routing Using Framework

Node has many frameworks for web applications. In this section, we will use Express.js to set up Routing. Routing in  Express is defined using the Express app object that corresponds to HTTP objects:

  • app.get(): to handle HTTP Requests
  • app.post(): to handle POST Requests
  • app.all(): to handle all HTTP methods’
  • app.use(): to specify middleware as the callback function.

All the routing methods specified above have a callback function or handler functions that are executed when the application receives a request to the specified route or endpoint and HTTP Method. In simple terms, the application "listens" for requests that match the specified route and methods and when it detects a match. It calls the specified callback function

If you haven’t installed express, you can do so by running the following command.

npm install express --save

You may refer to the documentation for the installation guide.

For GET Request use app.get() method

The following code is an example of routes that are defined for the GET methods to the root of the app.

var express = require('express')
var app = express()
const port = 3000

// respond with Get request made when a GET
// request is made to the homepage
app.get('/', function(req, res){
    res.send('GET request made')
})

app.listen(port, ()=> {
    console.log("Port listening at 3000
")
})

The above program can be run using node app.js.

For POST Request use app.post() method

The following code is an example of routes that are defined for the POST methods to the root of the app.

var express = require('express')
var app = express()
const port = 3000
// respond with Get request made when a GET
// request is made to the homepage
app.post('/', function(req, res){
    res.send('POST request made')
})

app.listen(port, ()=> {
    console.log("Listening at port 300");
})

The output is:

The output is so because in the above program, no GET request is being made, instead a POST request is made. The fundamental difference between GET and POST requests is that GET is used to request data from a specified source while POST submits the processed data to a specified resource.

For Handling all HTTP methods

There is a special routing method, app.all(), used to load middleware functions at a path for all HTTP request methods. For example, the following handler is executed for requests to the route “/secret” whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the http module.

app.all('/secret', function (req, res, next) {
    console.log('Accessing the secret section ...')
    next() // pass control to the next handler
})

The next() is used to hand off the control to the next callback. Sometimes we use app.use() to specify the middleware function as the callback. 

Apart from the request methods, route paths can be specified for the endpoints where the request can be made. The route path can be strings, string patterns, or regular expressions.

This route path will match requests to the root node /

app.get('/', function (req, res) {
    res.send('root')
})

This route path will match the request to the /about

app.get('/about', function (req, res) {
    res.send('about')
})

This route path will match the request acd and abcd.

app.get('/ab?cd', function (req, res) {
    res.send('ab?cd')
  })

Frequently Asked Questions

Q1) What is Routing in Node.js?

Ans 1) Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). In simple terms, Routing allows targeting different routes or different URLs on our page.

Q2) What is Node.js?

Ans 2) Node.js is a runtime environment for executing JavaScript code and is often used to build backend services. It is built on top of the Chrome v8 engine.

Key Takeaways

In this blog, we discussed and implemented Routing in Node.js with and without Framework with some examples. Now it's your turn to get your hands dirty on it by practicing.

A common problem faced by all of us is that we prepare well, but during online assessments, we cannot solve the questions on time. To overcome this, Coding Ninjas have come up with an online mock test series. The mock tests for leading companies like Amazon, Microsoft, Google, Adobe, Flipkart, TCS, Wipro, and Accenture are free. Our team of experts has curated and designed these online mock test series to help you prepare better for your coding interview rounds. In this online test series, you will get multiple tests that include the latest coding interview questions. Start preparing for the 2021 Amazon, Microsoft, etc., tech interviews now.

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think