• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Understanding Routes in Express

  • June 22, 2023
  • CODE OF GEEKS
  • 0
Routes in Express
Routes in Express

When it comes to building complex web applications with Express, having a solid understanding of routers is crucial.

Routers in Express provide a modular and organized approach to handle different routes and requests within your application.

In this blog post, we’ll dive deep into the world of routers and explore how they can simplify your web application development process. So, let’s get started!



What are Routers in Express?

Express routers are a powerful feature that allows you to create modular, self-contained sets of routes within your application.

They provide a way to organize and structure your code by separating different routes and their associated logic into distinct files.

Routers act as middleware and can be used to handle specific routes or groups of related routes, making your code more maintainable and scalable.

Benefits of Using Routers

Using routers in Express offers several benefits for your web application development:

1. Modularity and Organization: Routers enable you to break down your application’s routes into separate files, making it easier to manage and maintain your codebase. Each router can focus on a specific set of routes, ensuring clean separation of concerns.

2. Code Reusability: Routers allow you to reuse common route handlers across different parts of your application. This eliminates code duplication and promotes a more efficient development workflow.

3. Route Grouping: With routers, you can group related routes together based on functionality or resource type. This makes it easier to manage and update specific sections of your application without affecting others.

4. Middleware Flexibility: Routers can define their own middleware functions, allowing you to apply specific middleware to a group of routes. This helps in implementing authentication, error handling, and other common functionalities in a centralized manner.



Desired Folder Structure

Express Application Folder Structure
Express Application Folder Structure

Implementing Routers in Express

Let’s explore how to implement routers in Express using a practical example:

1. Create a new file called users.js in your project directory.

2. In users.js, import the necessary modules and create a new router:

const express = require('express');
const router = express.Router();

3. Define the routes for the user-related functionality

router.get('/', (req, res) => {
  // Logic for handling user list retrieval
});

router.post('/', (req, res) => {
  // Logic for creating a new user
});

router.get('/:id', (req, res) => {
  // Logic for retrieving a specific user by ID
});

router.put('/:id', (req, res) => {
  // Logic for updating a user by ID
});

router.delete('/:id', (req, res) => {
  // Logic for deleting a user by ID
});


Export the router from the users.js file:

module.exports = router;

In your main application file (e.g., app.js), import the users.js router and use it for the desired route:

const usersRouter = require('./users');

//...

app.use('/users', usersRouter);

Here’s an implementation of an Express project that uses routers

Folder Structure (click)
- app/
  - controllers/
    - userController.js
  - models/
    - userModel.js
  - routes/
    - userRoutes.js
  - views/
    - index.ejs
- config/
  - database.js
- app.js
- package.json
- README.md
app/controllers/userController.js
// Example userController with a simple route handler
exports.getUsers = (req, res) => {
  // Logic for retrieving users
  const users = [
    { id: 1, name: 'John Doe' },
    { id: 2, name: 'Jane Smith' },
  ];

  res.json(users);
};
app/routes/userRoutes.js
const express = require('express');
const router = express.Router();

const userController = require('../controllers/userController');

// Route to retrieve users
router.get('/', userController.getUsers);

module.exports = router;
app/views/index.ejs
<!DOCTYPE html>
<html>
<head>
  <title>Express App</title>
</head>
<body>
  <h1>Welcome to the Express App!</h1>
  <p>Visit the <a href="/users">users route</a>.</p>
</body>
</html>
app.js
const express = require('express');
const app = express();

// Importing the userRoutes from the routes folder
const userRoutes = require('./app/routes/userRoutes');

// Middleware to parse JSON bodies
app.use(express.json());

// Mounting the userRoutes
app.use('/users', userRoutes);

// Starting the server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
package.json
{
  "name": "express-project",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}


With this setup, first install all the dependencies:

npm i

you can run the project by executing the following command in your project directory:

npm start

The server will start running on port 3000, and you can visit http://localhost:3000/users to see the users route in action. Additionally, visiting the root URL (http://localhost:3000) will display the index.ejs view.

Feel free to extend and modify this code to suit your specific needs and add more routes, controllers, and views as your project evolves.





Keywords to search: routes in express, defining routes in express, express routers, how to define routes in express, routing express.

  • Previous Express Middleware: Boosting Your Web Application’s Functionality
  • Next Building Your First Express Application: A Step-by-Step Guide

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.