Hướng dẫn thử thách
1 / 1
Express Middleware Review
## What is Middleware?
- **Middleware** is a function that executes during the lifecycle of a request to the server.
- Middleware has access to the **request object** (`req`), the **response object** (`res`), and the **`next` function**.
- Common uses: logging requests, handling errors, parsing incoming data, and serving static files.
- Middleware is executed in the order it is added to the app.
### How Middleware Works
1. A request is sent to the server.
2. Middleware functions process the request.
3. If middleware calls `next()`, control passes to the next middleware or route handler.
4. If middleware does not call `next()`, the request-response cycle stops.
```javascript
app.use((req, res, next) => {
console.log('Request URL:', req.url);
console.log('Request Method:', req.method);
next();
});
```
- `app.use()` adds middleware globally to the application.
## Application-Level Middleware
- **Application-level middleware** is bound to an instance of the Express app.
- Registered using `app.use()` or route-specific methods like `app.get()`, `app.post()`, etc.
- Executes for every incoming request unless restricted to a specific route.
- Use cases: logging, authentication, and error handling across multiple routes.
```javascript
app.use((req, res, next) => {
console.log('Request received at:', new Date());
next();
});
```
## Router-Level Middleware
- **Router-level middleware** is bound to an instance of `express.Router()` instead of the main app.
- Applied using `router.use()` and only affects routes handled by that router.
- Helps modularize the app into isolated route modules.
- Mount a router with `app.use('/path', router)` to scope the middleware to specific routes.
```javascript
const router = express.Router();
router.use((req, res, next) => {
console.log('Request made to /menu route');
next();
});
router.get('/drinks', (req, res) => {
res.send('Welcome to the drinks menu!');
});
app.use('/menu', router);
```
## Error-Handling Middleware
- **Error-handling middleware** is a special middleware used to catch errors during the request-response cycle.
- It has **four parameters**: `err`, `req`, `res`, and `next`. The four-parameter signature is what tells Express this is an error handler.
- Invoked when an error is passed to `next(err)`.
- Should be placed **at the end** of the middleware stack, after all other middleware and routes.
```javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
```
## Built-in and Third-Party Middleware
### Built-in Middleware
- **`express.json()`**: parses incoming requests with JSON payloads.
```javascript
app.use(express.json());
```
- **`express.static()`**: serves static files such as images, CSS, and JavaScript.
```javascript
app.use(express.static('public'));
```
- **`express.urlencoded()`**: parses incoming requests with URL-encoded payloads (the format sent by HTML forms); makes parsed data available on `req.body`.
```javascript
app.use(express.urlencoded({ extended: true }));
```
### Third-Party Middleware
- **`cors`**: enables Cross-Origin Resource Sharing.
```javascript
app.use(cors());
```
- **`morgan`**: logs HTTP requests.
```javascript
app.use(morgan('tiny'));
```
- Both built-in and third-party middleware functions are added in the order they are called with `app.use()`.
Nhiệm vụ của bạn
Review the Express Middleware topics and concepts.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.html
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵