Routing in Express
Express.js makes it easy to define routes for various HTTP methods and handle dynamic and query parameters efficiently.
Defining Routes for HTTP Methods
Express supports multiple HTTP methods like GET, POST, PUT, and DELETE. Here’s how you can define routes for these methods:
const express = require("express");const app = express();
// Handling GET requestapp.get("/home", (req, res) => { res.send("Welcome to the homepage!");});
// Handling POST requestapp.post("/login", (req, res) => { res.send("Login Successful");});
// Handling PUT requestapp.put("/user/:id", (req, res) => { res.send(`User ${req.params.id} updated`);});
// Handling DELETE requestapp.delete("/user/:id", (req, res) => { res.send(`User ${req.params.id} deleted`);});Creating Dynamic Routes with URL Parameters
Dynamic routes allow you to capture values from the URL. This is done using URL parameters, which are defined with a colon (:) prefix.
app.get("/users/:id", (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`);});- The
:idpart of the route captures the value from the URL. - The captured value can be accessed using
req.params.id.
Handling Query Parameters
Query parameters are key-value pairs appended to the URL after a ?. Express allows you to access these parameters using req.query.
app.get("/search", (req, res) => { const searchTerm = req.query.term; res.send(`Search term: ${searchTerm}`);});- The query parameter term is accessed using req.query.term.
- This allows handling of requests like /search?term=express.
Route Grouping using express.Router()
For modularizing routes, use express.Router() to group routes logically.
const express = require("express");const router = express.Router();
// Define routes for /usersrouter.get("/", (req, res) => { res.send("List of users");});
router.post("/", (req, res) => { res.send("Create a new user");});
// Use the router in the appapp.use("/users", router);- GET /users serves the list of users.
- POST /users creates a new user.