Express Routing Basics
# CHAPTER 5
Express Routing Basics
1. Introduction
A web server is useless if it only has one page. Modern applications require dozens of endpoints: one to view a profile, one to update a password, and one to delete an account. Routing refers to determining how an application responds to a client request to a particular endpoint. In this chapter, we will master Express routing, covering the core HTTP methods, capturing dynamic data from URLs, and learning how to structure API endpoints.2. Learning Objectives
By the end of this chapter, you will be able to:- Map endpoints using GET, POST, PUT, and DELETE methods.
-
Define dynamic route parameters (e.g.,
/users/:id).
-
Extract data securely from
req.params.
- Handle 404 "Not Found" scenarios for undefined routes.
3. Beginner-Friendly Explanation
Imagine your Express server is an enormous filing cabinet with thousands of drawers. When a user wants a specific file, they cannot just yell "Give me a file!" They must specify the action and the location.- Action (HTTP Method): "I want to READ." (GET)
-
Location (The Path): "Drawer named 'Users'." (
/users)
GET /users, the receptionist knows exactly which drawer to open. If the user says DELETE /users, the receptionist knows to throw the drawer in the trash.
4. Basic Routing (The CRUD Verbs)
Express provides methods that perfectly match standard HTTP verbs.*Notice how the URL path (/api/articles) is exactly the same! The only difference is the HTTP Method. This is the core principle of REST API design.*
5. Dynamic Route Parameters (req.params)
If you want to view the profile of User #42, you do not write a hardcoded route for app.get('/users/42'). You use a Route Parameter by prefixing a word with a colon (:).
*If a user visits /api/users/99, the browser will display "You requested the profile for user ID: 99".*
6. Multiple Route Parameters
You can chain multiple dynamic parameters together. For example, finding a specific post by a specific user.*(URL: /api/users/5/posts/10)*
7. Handling 404 Not Found
Express evaluates routes from top to bottom. If a user visits a URL that does not match *any* of your defined routes, Express hangs or sends a generic error. You can add a "catch-all" route at the very bottom of your file to handle 404 errors gracefully.8. Backend Workflow: API Naming Conventions
When defining routes for an API, professional developers use plural nouns, not verbs.-
Bad:
app.get('/api/get-users')
-
Good:
app.get('/api/users')
-
Bad:
app.post('/api/create-post')
-
Good:
app.post('/api/posts')
9. Best Practices
-
Route Ordering: Because Express reads top-to-bottom, static routes MUST go before dynamic routes. If you place
app.get('/users/:id')beforeapp.get('/users/admin'), and a user visits/users/admin, Express will think the word "admin" is a dynamic ID and trigger the wrong route!
10. Common Mistakes
-
Testing POST/PUT/DELETE in a Browser: Beginners often write an
app.post('/api/users')route, type that URL into Google Chrome, and get a "Cannot GET /api/users" error. Web browsers can only make GET requests via the address bar. To test POST, PUT, or DELETE routes, you must use HTML Forms or a tool like Postman.
11. Exercises
-
1.
Explain the architectural benefit of using identical URLs (e.g.,
/api/products) with different HTTP methods (GET vs POST) rather than writing unique URLs for every action (e.g.,/api/get-productsand/api/create-product).
12. Coding Challenges
-
Challenge: Write an Express route that handles a
DELETErequest for a specific product. The URL should utilize a dynamic parameter for the product ID. Inside the route, useres.send()to return a message confirming the deletion of that specific ID.
13. MCQs with Answers
Which object in Express holds the dynamic values extracted from the URL path, such as the 42 in /users/42?
Why must a "catch-all" 404 route (using *) be placed at the very bottom of the Express route definitions?
14. Interview Questions
-
Q: Explain how Route Parameters (
req.params) work in Express. Provide a use case where chaining multiple parameters in a single URL is necessary.
- Q: Why is the physical ordering of route definitions critical in an Express application, particularly concerning dynamic wildcards versus static endpoints?
15. FAQs
Q: Can a route parameter be optional? A: Yes! You can add a question mark? after the parameter name. E.g., app.get('/api/users/:id?'). If the user visits /api/users/, the req.params.id will simply be undefined.
16. Summary
In Chapter 5, we mastered traffic direction. We mapped the standard REST HTTP verbs (GET, POST, PUT, DELETE) to specific application logic. We learned how to write dynamic, reusable endpoints using Route Parameters (req.params), allowing a single block of code to handle requests for thousands of different database records. Finally, we learned how to gracefully handle invalid traffic using a catch-all 404 route.
17. Next Chapter Recommendation
We know how to define routes, but so far we are only returning plain text usingres.send(). Modern APIs must return formatted data. Proceed to Chapter 6: Handling Requests and Responses.