Catalog / Express.js Cheatsheet
Express.js Cheatsheet
A comprehensive cheat sheet for Express.js, covering essential concepts, middleware, routing, and common tasks for building web applications and APIs.
Core Concepts & Setup
Basic Setup
Installation:
|
Basic App Structure:
|
Running the App:
|
Middleware Basics
|
Applies middleware to all routes. Middleware functions have access to the request object ( |
|
A function to pass control to the next middleware function. Crucial for chaining middleware. |
Example: |
|
Request and Response Objects
|
Access route parameters (e.g., |
|
Access query string parameters (e.g., |
|
Access the request body (requires body-parsing middleware). |
|
Sends the HTTP response. The |
|
Sends a JSON response. |
|
Sets the HTTP status code. |
Routing
Basic Routing
Route Methods:
|
Route Parameters:
|
Chaining Route Handlers:
|
Route Paths
|
Matches only the path |
|
Matches any single character except |
|
The |
|
Matches only if username contains letters. |
Using `next()` in Routes
|
This allows you to define multiple handlers for a single route, performing different operations in sequence. |
Middleware
Built-in Middleware
|
Serves static files (e.g., images, CSS, JavaScript) from a directory.
|
|
Parses incoming requests with JSON payloads and is based on
|
|
Parses incoming requests with URL-encoded payloads and is based on
|
Third-Party Middleware
Examples:
|
Example with Morgan:
|
Custom Middleware
You can create your own middleware functions to handle specific tasks.
|
Middleware can also be applied to specific routes:
|
Advanced Topics
Error Handling
Express comes with a built-in error handler. To use it, you simply pass an
|
Remember to place the error-handling middleware after all other middleware and route handlers. |
Template Engines
Setting up EJS |
|
Popular Engines |
Besides EJS, other template engines include Pug (formerly Jade), Handlebars, and Mustache. |
Best Practices
|