Node.js : Day 7

Rahul Kumar
6 min readDec 20, 2024

Routing, Need of routing, ways of defining routing in express, route parameter, query parameters and many more…

Q. Why we need of routing?

  • To explore the various features available in any web application, we need to request the correct URL for the specific feature we are currently interested in.
  • For a web application, all the URLs will reach the same server, but the paths will be different. It is the server’s responsibility to route the URLs to the appropriate features depending on the path.
  • Depending on the path and HTTP method, different responses are sent back by the server. The server needs to decide which response needs to be sent for a particular path in the URL.

Express provides routing API to help to manage these requirements whenever a request is received by the server.

What is Routing?

Defining the endpoints of an application and the way the application responds to incoming client requests are referred to as routing.

A route is nothing but a mixture of a URI, HTTP request method, and some handlers for that particular path.

Q. Explain Basic architecture of Express Routing?

Whenever a client sends a request to the server, that request is forwarded to the corresponding route handler function. The function processes the request and then generates the response that is to be sent back to the client. The client will be able to see the response in the browser.

How Route can be defined?

A route can be defined as shown below:

router.method(path,handler)
  • router: express instance(app) or router instance.
  • method: one of the HTTP verbs.
  • path: is the route where the request runs.
  • handler: is the callback function that gets triggered whenever a request comes to a particular path for a matching request type.

Routing can be defined using two ways

  • Application(express) Instance
  • Router class of Express
  1. Routing by using application instance:

Routing can be done by using the application object. Look at the below code snippet which does the routing using the application object.

const express = require('express');

const app = express();

// router defined by using application instance

/*
app --> router

get() --> Method

'/' --> path

(req,res) => {
res.send("This is homepage");
} ---> handler
*/

app.get('/', (req,res) => {
res.send("This is homepage");
});

app.get('/about', (req,res) => {
res.send("This is About page");
});

app.listen(3000, () => {
console.log("App is runnning on port 3000");
})

2. Routing by using Router class of Express

Router class helps in grouping the route handlers together for a site and allows them to access them using a common route-prefix.

Let’s use the express.Router class:

route.js file:

const express = require('express');

const router = express.Router(); // Creating an Instance of express Router

router.get('/', (req,res) => {
res.send("This is homepage");
});

router.get('/about', (req,res) => {
res.send("This is Abaout page");
});

module.exports = router;

app.js

const express = require('express');

const router = require('./routes/route');

const app = express();

app.use('/', router); // using the express router defined in route.js file

app.listen(3000, () => {
console.log("App is running on port 3000");
});

Route Method:

The application object has different methods corresponding to each of the HTTP verbs (GET, POST, PUT, DELETE). These methods are used to receive HTTP requests.

  • get(): Use this method for getting data from the server.
  • post(): Use this method for posting data to a server.
  • put(): Use this method for updating data in the server.
  • delete(): Use this method to delete data from the server.
  • all(): This method acts like any of the above methods. This can be used to handle all requests.

example:

app.get('/', handler);

app.post('/', handler);

app.put('/', handler);

app.delete('/', handler);

app.all('/', handler);

Route Path:

Route path is the part of the URL which defines the endpoint of the request.

  • For the URL “http://localhost:3000/" ➡ ‘/’ is the endpoint
  • For the URL “http://localhost:3000/about" ➡ ‘/about’ is the endpoint.

The path can also be string patterns or regular expressions.

Route handler:

Route handlers can be defined as functions that get executed every time the server receives a request for a particular URL path and HTTP method.

The route handler function needs at least two parameters: request object and response object.

Request object(req):

The HTTP request object is created when a client makes a request to the server. The variable named req is used to represent this object.

The request object in Express provides many properties and methods to access the request-related information sent by the client to the server.

  1. req.params: An object containing properties mapped to the named route parameters. For example, if you have a route /users/:userId, req.params.userId would give you the value of userId parameter.
  2. req.query: An object containing properties mapped to the query string parameters in the URL. For example, in the URL /search?q=express, req.query.q would give you the value of the q parameter.
  3. req.body: An object containing the parsed request body. This is available only when you use middleware like body-parser or similar to parse the request body. It allows you to access form data or JSON payloads sent by the client.
  4. req.headers: An object containing the HTTP headers sent by the client.
  5. req.method: A string representing the HTTP method of the request (e.g., ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’, etc.).
  6. req.path: A string representing the path portion of the URL requested by the client.
  7. req.url: A string representing the full URL requested by the client, including query parameters.
  8. req.cookies: An object containing the cookies sent by the client.
  9. req.ip: A string representing the IP address of the client making the request.
  10. req.protocol: A string representing the protocol used by the client (e.g., ‘http’ or ‘https’).

Response object(res):

  • The HTTP response object has information about the response sent from the server to the client.
  • The response object is created along with the request object and is commonly represented by a variable named res.

The route handler function sends a response using res.send() method whenever a GET request is received.

The response object in Express also supports many methods for sending different types of responses.

Below are some commonly used methods of the response object.

Route parameters:

Route parameters are useful for capturing the values indicated at certain positions in the URL. These are defined as named URL segments.

Example:

If we want to capture the portion of the URL which contains “Razz”, then

we can access by using syntax:

req.params.< parameter_name >

Example:

router.get('/user/:username', async (req, res) => {
const name = req.params.username;
res.send(`Welcome ${name}`);
};);

Example 2:

If URL is ‘http://localhost:3000/user/Smith/23'

If we want to capture route parameter from this url.

router.get('/user/:username/:id', async (req, res) => {
const username = req.params.username;
res.send(`Welcome ${username} with id ${req.params.id}`);
};)

Query Parameters:

  • Query strings are the data appended as part of the request URL.
  • Query strings start with a question mark(?) and the name-value pair in it is separated by an ampersand(&).

For example, in the below URL,

'http://localhost:3000/login?username=john&email=john40i.com&login=Login',

The querystring is

“username=john&email=john40i.com&login=Login”

We can access query parameters by using the syntax:

request.query.<querystring name-value pair>

Example:

app.get('/login', async (req, res) => {
const name = req.query.username;
res.send(`You have registered in with username ${name}}`);
});

Thanks…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Rahul Kumar
Rahul Kumar

Written by Rahul Kumar

MERN Stack Developer building scalable web apps with MongoDB, Express.js, React.js, Node and TS. Sharing insights and best practices for modern web development.

No responses yet

Write a response