Stanford CS142 笔记 - Express.js
Introduction
1 |
|
The instance expressAPP
provides all the methods to:
- Route HTTP requests (map different URLs to different logic)
- Render HTML
- Configure middleware (Middleware are functions that process requests before they reach routes)
Express Routing
Routing allows you to define actions for specific HTTP methods:
1 |
|
The order of execution in Express routes is determined by the order in which they are defined in your code. Here’s the principle:
- When a request is received, Express evaluates routes from top to bottom in the order they are defined in the code.
- It stops at the first match it finds (this is called short-circuiting).
httpRequest Object
It represents the HTTP request sent by the client.
request.params
: Access route parameters1
2
3expressApp.get('/user/:user_id', (req, res) => {
console.log(req.params.user_id); // Logs the user_id
});request.query
: Contains query string parameters from the URL
1 |
|
request.body
: Contains the body of POST or PUT requests
httpResponse Object
Represents the response sent back to the client.
response.send(content)
: Sends a response to the client (automatically ends the response). e.g.,res.send('Hello, world!');
.response.status(code)
: Sets the HTTP status code of the response. e.g.,res.status(404).send('Not Found');
.response.set(field, value)
: Sets a custom HTTP response header.response.end()
: Ends the response process.channing: e.g.,
res.status(200).send('OK');
Example Usage:
1 |
|
Middleware
Middleware are functions that can:
- Intercept HTTP requests.
- Perform operations on the request/response objects.
- Either terminate the request-response cycle or pass control to the next middleware in the stack using next().
1 |
|
app.all()
: Matches all HTTP methods for the route.
1 |
|
app.use()
: Registers middleware for all routes.
e.g., app.use(express.json());
, Use built-in middleware for parsing JSON.