Hướng dẫn thử thách
1 / 8
What Is Routing and How Do Route Methods Work in Express?
Now that you've built a basic Express app, it's time to take a closer look at routing and how it works.
In Express, routing is how you define the endpoints of a web application. You can think of routes as rules that tell the app how to respond when a user visits a specific URL.
Let's look at our simple Express app again:
```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}`);
});
```
In this example, the app defines a route for the root URL (`/`). When a client sends a GET request to this path, the server responds with the text `Hello World!`. The app then starts listening for incoming requests on port `3000`.
But there are other route methods.
Express lets you handle different types of HTTP requests by using different routing methods. The most common ones are:
* `app.get()` – retrieves data
* `app.post()` – creates new data
* `app.put()` – updates existing data
* `app.delete()` – deletes data
Each method defines how your application should respond to a specific HTTP request at a specific route.
Here are a few simple examples:
```javascript
app.post("/submit", (req, res) => {
res.send("Form submitted!");
});
app.put("/update", (req, res) => {
res.send("Item updated!");
});
app.delete("/delete", (req, res) => {
res.send("Item deleted!");
});
```
In each case, Express listens for a request with a particular HTTP method and URL path, then runs the corresponding handler function to send a response back to the client.
You can test these routes using tools like Postman or `curl`, which let you send different types of HTTP requests to your server.
And that’s routing in Express - it’s simply about defining how your application responds to different requests.
Vượt qua bài kiểm tra hiện tại để mở khóa bài tiếp theo.
main.sql
UTF-8 • Tab Size: 2Kiểm tra bài:⌘↵