Hướng dẫn thử thách
1 / 5
What is Middleware and How Does it Work?
Middleware is an essential concept in Express, and it allows us to handle requests and responses between the client and server. Middleware functions have access to the request object, the response object, and the next function in the application's request-response cycle.
Let's break it down:
## What is Middleware?
Middleware is essentially a function that executes during the lifecycle of a request to the server. It performs various tasks such as logging requests, handling errors, parsing incoming requests, or serving static files.
Express provides a convenient way to define middleware that processes incoming requests before they reach route handlers.
How Middleware Works:
When a request is made to an Express application, middleware is executed in the order it is added. The flow looks like this:
* Request is sent to the server.
* Middleware functions process the request.
* If the middleware calls `next()`, it passes control to the next middleware or route handler.
* If the middleware doesn't call `next()`, the request-response cycle stops.
```js
const express = require('express')
const app = express()
// Simple middleware that logs request info
app.use((req, res, next) => {
console.log('Request URL:', req.url)
console.log('Request Method:', req.method)
next() // Passes control to the next middleware
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})
```
`app.use()`: Adds middleware globally to your application.
In this example, the middleware logs request details and calls `next()` to proceed to the next middleware or route handler.
Middleware is a powerful feature in Express that allows you to intercept and modify requests at various points. You can use middleware to handle things like logging, authentication, or even modify request and response objects before they reach your route handlers.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.sh
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵