Do you think IIT Guwahati certified course can help you in your career?
No
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.
What is Routing in Node.js ?
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 Express Framework
Let’s take an example wherein there is a simple server setup using Node.js in the following app.js file.
JavaScript
JavaScript
// 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')
You can also try this code with Online Javascript Compiler
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
JavaScript
JavaScript
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");
You can also try this code with Online Javascript Compiler
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.
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 Express 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.
The following code is an example of routes that are defined for the POST methods to the root of the app.
JavaScript
JavaScript
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"); })
You can also try this code with Online Javascript Compiler
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
Why do we use routing in node JS?
We use routing in Node.js to handle different HTTP requests by directing them to specific functions or endpoints. Routing helps manage various actions, such as displaying content, submitting forms, or interacting with databases, based on the request URL.
What is the difference between node and route?
Node refers to Node.js, a JavaScript runtime for building server-side applications, while a route is a defined path in an application that maps a specific URL to a function or action. Node.js processes routes to determine how to respond to client requests.
What are the common HTTP methods used in routing?
Common HTTP methods used in routing include GET (to retrieve data), POST (to submit data), PUT (to update data), and DELETE (to remove data). These methods allow for different actions based on the type of request sent to the server.
Conclusion
In this blog, we covered how to implement routing in Node.js both with and without a framework, along with examples. Now, it's your turn to dive in and practice by applying these concepts to build your own routes.
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.