Stanford CS142 笔记 - Express.js
Introduction
let express = require('express');
let expressApp = express();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:
expressApp.get('/path', callback);
expressApp.post('/path', callback);
expressApp.put('/path', callback);
expressApp.delete('/path', callback);
expressApp.all('/path', callback); // Handles requests for all HTTP methods (e.g., GET, POST, etc.) on a specific path.
expressApp.get('/user/:user_id', (req, res) => {
res.send(`User ID is ${req.params.user_id}`);
});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 parameters
expressApp.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
expressApp.get('/search', (req, res) => {
console.log(req.query); // { foo: '9' } ?foo=9 becomes {foo: '9'}
});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:
app.get('/user/:id', (request, response) => {
let id = request.params.id;
let user = cs142models.userModel(id);
if (user === null) {
console.log('User with _id:' + id + ' not found.');
response.status(400).send('Not found');
return;
}
response.status(200).send(user);
return;
});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().
app.all('/specific-route', (req, res, next) => {
console.log('Middleware for /specific-route');
next(); // Pass control to the next handler or middleware
});app.all(): Matches all HTTP methods for the route.
app.use((req, res, next) => {
console.log('Global Middleware');
next();
});app.use(): Registers middleware for all routes.
e.g., app.use(express.json());, Use built-in middleware for parsing JSON.
Stanford CS142 笔记 - Express.js
http://example.com/2024/11/26/CS142/expressjs/