Routing in Express.js
⏱ Estimated reading time: 2 min
Routing in Express.js refers to defining endpoints (URLs) of your application and determining how the server responds to client requests.
Routes are essential for building REST APIs or web applications.
1. Basic Routing
Explanation:
-
app.get(path, callback)– Handles GET requests to a specific path. -
res.send()– Sends a response to the client.
2. Route Methods
Express supports all HTTP methods:
| Method | Usage Example |
|---|---|
| GET | app.get('/users', ...) |
| POST | app.post('/users', ...) |
| PUT | app.put('/users/:id', ...) |
| DELETE | app.delete('/users/:id', ...) |
| PATCH | app.patch('/users/:id', ...) |
Example: CRUD operations for users
3. Route Parameters
Route parameters allow you to capture values in the URL.
-
URL:
/users/123→ Response:User ID is 123
4. Query Parameters
Query parameters are passed after ? in the URL.
-
URL:
/search?q=express→ Response:You searched for: express
5. Chaining Route Handlers
You can chain multiple handlers for a single route:
6. Router-Level Routing
Express allows you to create modular route handlers using express.Router().
-
/user/profile→User Profile -
/user/settings→User Settings
7. Best Practices
-
Use Router for modular code.
-
Use consistent route naming (plural nouns for resources:
/users,/posts). -
Separate routes into different files for large projects.
Routing is the backbone of any Express.js application, and mastering it is crucial for building RESTful APIs and full-stack apps.
Register Now
Share this Post
← Back to Tutorials