Basic Routing & HTTP Methods
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI and a specific HTTP request method.
1 RESTful Endpoint Routings
Express supports all HTTP verbs including GET, POST, PUT, and DELETE out of the box:
JavaScript — server.js
const express = require("express");
const app = express();
// GET request - retrieve info
app.get("/api/users", (req, res) => {
res.send("Fetching all user profiles...");
});
// POST request - create new resource
app.post("/api/users", (req, res) => {
res.send("Creating a new user profile...");
});
// PUT request - replace/update existing resource
app.put("/api/users", (req, res) => {
res.send("Updating user profile completely...");
});
// DELETE request - delete resource
app.delete("/api/users", (req, res) => {
res.send("Deleting user profile...");
});
2 app.all() and Route Parameters Pattern
The app.all() method is useful for loading middleware functions at a path for all request methods. Express also supports route pattern matching with parameters:
JavaScript — Pattern Matching
// Matches any HTTP method on /secret path
app.all("/secret", (req, res, next) => {
console.log("Accessing the secret section...");
next(); // pass control to the next handler
});
// Route paths with string patterns (matches /acd and /abcd)
app.get("/ab?cd", (req, res) => {
res.send("ab?cd match!");
});
3 Code Challenge
Challenge: Write a route path pattern that matches both
/profile and /user-profile dynamically using a regular expression or wildcard matching pattern in Express.