Hướng dẫn thử thách
1 / 1
Introduction to Express Review
## What Is Express.js?
- **Express**: A minimal and flexible web framework built on top of Node.js that makes it easier to build web servers and APIs.
- **Install Express**: `npm install express`
- **What you can build with Express**: web apps, RESTful APIs, SPA backends, middleware-heavy services, and anything server-side with HTTP.
- **Middleware**: Code that runs between receiving a request and sending a response. Used for error handling, input validation, modifying request or response data, and more. Multiple middleware functions can be chained together.
- **Plugins**: External npm modules that extend Express, usually implemented as middleware.
## Creating a Basic Express App
```javascript
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
```
- `require("express")` — loads the Express library.
- `express()` — factory function that creates and returns a new Express application instance.
- `app` — the main server object with access to methods like `.get()`, `.post()`, and `.listen()`.
- `port` — the network endpoint the app listens on. Port `3000` is common for local development.
- `app.listen(port, callback)` — starts the server and begins listening for incoming HTTP requests.
## Routing in Express
- **Route**: A rule that tells the app how to respond when a client requests a specific URL with a specific HTTP method.
- **Route methods**: `app.get()`, `app.post()`, `app.put()`, `app.delete()` — each handles requests with the matching HTTP method.
- **Static route path**: A fixed URL like `/home` or `/menu/drinks`.
- **Dynamic route path (route parameter)**: A placeholder in the URL that captures a value, prefixed with `:`, for example `/post/:postId`.
- **`req.params`**: An object containing the dynamic values captured from the URL. For example, a request to `/post/42` gives `req.params.postId === "42"`.
### Route Handlers
- A **route handler** is the callback function `(req, res) => { ... }` that runs when a request matches a route.
- `req` — contains information about the incoming request (params, query strings, headers, body).
- `res` — used to send a response back to the client.
## Response Methods
| Method | What it does |
| --- | --- |
| `res.send()` | Sends a response — plain text, HTML, JSON, or binary data. |
| `res.json()` | Sends a JSON response; automatically converts a JavaScript object. |
| `res.status(code)` | Sets the HTTP status code; usually chained with `res.send()` or `res.json()`. |
| `res.redirect(url)` | Redirects the client to a different URL. |
| `res.render(view, data)` | Renders a template engine view and sends the resulting HTML. |
## Chainable Route Handlers with `app.route()`
- `app.route(path)` groups multiple HTTP method handlers for the same path to avoid repeating it.
```javascript
app
.route("/user")
.get((req, res) => { res.send("Fetching user data"); })
.post((req, res) => { res.send("Creating a user"); })
.put((req, res) => { res.send("Updating the user"); })
.delete((req, res) => { res.send("Deleting the user"); });
```
## Modular Routing with `express.Router()`
- `express.Router()` creates a router object — like a mini Express app — that you can define routes on and then mount in the main app.
- Mount a router with `app.use(path, router)`. Routes inside the router are relative to the mount path.
- **Benefits**: separates concerns, keeps the main file clean, and makes routes reusable and easier to scale.
```javascript
// userRoutes.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => { res.send("List of users"); });
router.get("/:id", (req, res) => { res.send(`User ${req.params.id}`); });
module.exports = router;
// app.js
app.use("/users", userRoutes); // mounts the router at /users
```
## Serving Static Files
- **Static files**: Assets like images, CSS, and client-side JavaScript that are served directly without server-side processing.
- `express.static(directory)` — built-in middleware that serves files from a specified folder.
- If a requested file is not found, Express automatically responds with a 404.
- No route definitions are needed for individual static files.
```javascript
app.use(express.static(path.join(__dirname, "public")));
```
- You can serve from multiple directories by calling `app.use()` multiple times, optionally with a mount path:
```javascript
app.use(express.static(path.join(__dirname, "public")));
app.use("/images", express.static(path.join(__dirname, "images")));
```
Nhiệm vụ của bạn
Review the Introduction to Express topics and concepts.
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:⌘↵