Stanford CS142 笔记 - Express.js

Introduction

1
2
let express = require('express');
let expressApp = express();

The instance expressAPP provides all the methods to:

  1. Route HTTP requests (map different URLs to different logic)
  2. Render HTML
  3. 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
2
3
4
5
6
7
8
9
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
    1
    2
    3
    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
1
2
3
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:

1
2
3
4
5
6
7
8
9
10
11
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:

  1. Intercept HTTP requests.
  2. Perform operations on the request/response objects.
  3. Either terminate the request-response cycle or pass control to the next middleware in the stack using next().
1
2
3
4
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.
1
2
3
4
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
https://thiefcat.github.io/2024/11/26/CS142/Express-js/
Author
小贼猫
Posted on
November 26, 2024
Licensed under