Modularizing Routes with Express Router

As your application grows, managing routes in a single file can become cumbersome. Express Router allows you to create modular route handlers:

Create a separate file for routes (e.g., routes.js):

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

router.get('/', (req, res) => {
    res.send('Hello from Express routes!');
});

app.get('/users/:id', (req, res) => {
    const userId = req.params.id; // Access the parameter value
    res.send(`User with ID: ${userId} from routes`);
});

module.exports = router;

Importing and using the router in your main app (app.js):

Javascript
const express = require('express');
const app = express();

// Use environment variable or default to port 3000
const port = process.env.PORT || 3000;

// Import the router
const routes = require('./routes');

// Use the router for all paths starting with '/'
app.use('/', routes);


app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
});

Getting Started with Express JS

Express JS is a versatile, minimalist web framework for NodeJS that simplifies the development of back-end applications and APIs for web and mobile applications. Its flexibility and powerful features enable you to create robust and scalable web projects with minimal code, making it a popular choice among developers. Express is released as free and open-source software under the MIT License.

Table of Content

  • Installing Express JS
  • Running a simple web server in Express JS
  • Adding Routes for Handling request in Express JS
  • Adding Parameters to Routes in Express JS
  • Modularizing Routes with Express Router:
  • Adding Middleware for Processing Requests in Express JS
  • Adding Error Handling Middleware in Express JS

Similar Reads

Prerequisites:

NPM & NodeJSJavaScript...

Installing Express JS:

Step 1: Create a project directory:...

Running a simple web server in Express JS:

require(‘express’): Imports the Express module.const app = express(): Creates an Express application instance, which serves as the foundation for building your web application.app.listen(port, callback): Starts the server and listens for requests on the specified port.process.env.PORT: Checks for an environment variable named PORT that might be set to a specific port number.callback: An optional function that is called when the server starts successfully....

Adding Routes for Handling request in Express JS:

Express provides methods to define routes, which map specific URL paths to corresponding server-side functions (handlers) that handle incoming requests.These methods come in different flavors for various HTTP methods (GET, POST, PUT, DELETE, etc.):app.get(path, handler): Defines a route that handles GET requests to the specified path. The handler function is called with two arguments:req: The request object containing information sent by the client (e.g., headers, parameters, body)....

Adding Parameters to Routes in Express JS:

You can capture dynamic values from URLs using parameters:...

Modularizing Routes with Express Router:

As your application grows, managing routes in a single file can become cumbersome. Express Router allows you to create modular route handlers:...

Adding Middleware for Processing Requests in Express JS:

Middleware are functions that have access to incoming requests and outgoing responses in your Express application. They allow you to perform common tasks across multiple routes or the entire application, such as logging, authentication, and error handling....

Adding Error Handling Middleware in Express JS:

Error Handling is crucial for a robust application. Express provides a way to catch errors thrown in your application code or middleware. Here’s an example of error handling middleware:...

Contact Us