Routing in NodeJS
Routing is the process of deciding how a server should respond to different requests made by users. When you visit a website or use an app, your browser sends a request to the server. Routing determines how the server handles these requests based on the URL you visit and the type of request (such as viewing a page, submitting a form, or deleting something).
There are mainly two ways to implement routing in NodeJS
1. Routing with the Native HTTP Module
In NodeJS, routing is done by directly using the built-in http module to create a server that listens for client requests. You manually handle different HTTP methods and URLs. This gives you full control over the request/response cycle, but it requires more boilerplate code and manual handling of request data.
How It Works
- You create an HTTP server with http.createServer().
- Inside the server's callback function, you inspect the incoming request (req), including its URL (req.url) and HTTP method (req.method).
- Based on these parameters, you can determine which functionality to execute (i.e., which route to trigger).
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
const url = req.url;
if (url === '/about') {
res.write(' Welcome to about us page');
res.end();
}
else if (url === '/contact') {
res.write(' Welcome to contact us page');
res.end();
}
else {
res.write('Hello World!');
res.end();
}
}).listen(3000, function () {
console.log("server start at port 3000");
});
To start the application run the following command
node index.js
Output
Routing Using Express Framework
Express.js is a minimalist web framework for NodeJS that simplifies routing and server-side application management. With Express, routing becomes simpler and more intuitive.
You don’t need to manually check request methods and URLs; instead, Express provides dedicated methods for handling different HTTP requests, such as app.get(), app.post(), etc.
How It Works:
- Install Express using npm install express.
- Create an Express app by calling express().
- Define routes using Express methods like app.get(), app.post(), etc.
- Start the server and listen for incoming requests.
For a GET request using the app.get() method:
const express = require('express')
const app = express()
app.get('/', function(req, res) {
res.send('Hello Geeks')
})
For POST requests use the app.post() method:
const express = require('express')
const app = express()
app.post('/', function(req, res) {
res.send('Hello Geeks')
})
The below code example is using express framework for creating routes
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/about', (req, res) => {
res.send('Welcome to about us page');
});
app.get('/contact', (req, res) => {
res.send('Welcome to contact us page');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Output