Routing is a fundamental concept in web development, and Express.js provides a robust and flexible way to handle routing in your Node.js applications. In this section, we will cover the basics of routing in Express, including defining routes, handling different HTTP methods, and organizing routes in a modular way.

Key Concepts

  1. Routes: Define the endpoints of your application and specify how to handle requests to those endpoints.
  2. HTTP Methods: Differentiate between various types of requests (GET, POST, PUT, DELETE, etc.).
  3. Route Parameters: Capture dynamic values from the URL.
  4. Middleware: Functions that execute during the lifecycle of a request to the server.

Defining Routes

In Express, routes are defined using the app object. Here’s a basic example:

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

app.get('/', (req, res) => {
  res.send('Hello, World!');
});

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

Explanation

  • app.get('/'): Defines a route that listens for GET requests on the root URL (/).
  • req and res: Represent the request and response objects, respectively.
  • res.send('Hello, World!'): Sends a response back to the client.

Handling Different HTTP Methods

Express allows you to handle different HTTP methods using corresponding functions like app.get(), app.post(), app.put(), and app.delete().

app.post('/submit', (req, res) => {
  res.send('Form submitted!');
});

app.put('/update', (req, res) => {
  res.send('Data updated!');
});

app.delete('/delete', (req, res) => {
  res.send('Data deleted!');
});

Explanation

  • app.post('/submit'): Handles POST requests to the /submit endpoint.
  • app.put('/update'): Handles PUT requests to the /update endpoint.
  • app.delete('/delete'): Handles DELETE requests to the /delete endpoint.

Route Parameters

Route parameters allow you to capture values from the URL and use them in your route handlers.

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});

Explanation

  • :id: Defines a route parameter named id.
  • req.params.id: Accesses the value of the id parameter from the URL.

Organizing Routes

As your application grows, it’s a good practice to organize your routes into separate files or modules. This makes your code more maintainable and easier to understand.

Example: Organizing Routes in a Separate File

  1. Create a new file routes.js:
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('Home Page');
});

router.get('/about', (req, res) => {
  res.send('About Page');
});

module.exports = router;
  1. Use the routes in your main application file app.js:
const express = require('express');
const app = express();
const routes = require('./routes');

app.use('/', routes);

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

Explanation

  • express.Router(): Creates a new router object.
  • router.get(): Defines routes on the router object.
  • app.use(): Mounts the router on the specified path.

Practical Exercise

Task

Create an Express application with the following routes:

  1. A GET route at / that responds with "Welcome to the Home Page".
  2. A GET route at /users that responds with "User List".
  3. A GET route at /users/:id that responds with "User ID: [id]".

Solution

  1. Create a new file app.js:
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the Home Page');
});

app.get('/users', (req, res) => {
  res.send('User List');
});

app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});

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

Explanation

  • The application defines three routes: /, /users, and /users/:id.
  • Each route sends a different response based on the URL and parameters.

Common Mistakes and Tips

  • Forgetting to start the server: Always ensure you have app.listen() to start your server.
  • Incorrect HTTP methods: Make sure you use the correct method (GET, POST, etc.) for the intended action.
  • Route order: Routes are matched in the order they are defined. More specific routes should be defined before more general ones.

Conclusion

In this section, we covered the basics of routing in Express, including defining routes, handling different HTTP methods, using route parameters, and organizing routes in a modular way. Understanding these concepts is crucial for building robust and maintainable web applications with Express.

Next, we will dive into error handling in Express, which is essential for creating reliable applications.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved