Installation:
npm install express --save
A comprehensive cheat sheet for Express.js, covering essential concepts, middleware, routing, and common tasks for building web applications and APIs.
Installation:
|
Basic App Structure:
|
Running the App:
|
|
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: |
|
|
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. |
Route Methods:
|
Route Parameters:
|
Chaining Route Handlers:
|
|
Matches only the path |
|
Matches any single character except |
|
The |
|
Matches only if username contains letters. |
|
This allows you to define multiple handlers for a single route, performing different operations in sequence. |
|
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
|
Examples:
|
Example with Morgan:
|
You can create your own middleware functions to handle specific tasks.
|
Middleware can also be applied to specific routes:
|
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. |
Setting up EJS |
|
Popular Engines |
Besides EJS, other template engines include Pug (formerly Jade), Handlebars, and Mustache. |
|