Open In App

What is routing in Express?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Express routing is about showing your app how to respond to different URLs. It involves associating HTTP methods with specific functions to handle requests. This helps organize and control the flow of your web application.

Routing in Express:

  • Routing in Express is like showing your web app where to go.
  • It’s about deciding what your app should do when users go to various URLs.
  • You get to set the actions for things like going to the homepage, submitting forms, or clicking links.
  • Express makes it simple by letting you create rules that connect to specific parts of your code.
  • In essence, it’s like telling your app, “Hey, when someone goes here, do this specific thing.”

Steps to Implement Routing in Express:

Step 1: Initialising the Node App using the below command:

npm init -y

Step 2: Installing express in the app:

npm install express

Example: Below is the example of routing in express:

Javascript




// server.js
const express = require('express');
const app = express();
const PORT = 4000;
 
// define route
app.get('/home',
    (req, res) => {
        res.send(
            '<h1>welcome to GeeksforGeeks!</h1>'
        );
    });
 
app.listen(PORT,
    () => {
        console.log(
            `Server is listening at http://localhost:${PORT}`
        );
    });


Start using the following command:

node server.js

Output:

Animation

Output

Advantages of Routing in Express:

  • Code Organization: Express routing simplifies code structure by managing functionalities separately.
  • Readability: It enhances code understanding by clearly defining how different URLs are handled.
  • Scalability: Routing allows for the easy addition of new features without major codebase changes.
  • SEO-friendly: Good routing means creating web addresses that search engines like, making your app more visible and user-friendly in search results.
  • RESTful API Design: Routing in Express is great for building powerful and scalable services, especially when creating APIs that follow the RESTful design principles.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads