路由
约 656 字大约 2 分钟
2025-07-25
路由指的是确定应用程序如何响应客户端对特定端点的请求,该端点是一个 URI(或路径)以及特定的 HTTP 请求方法(GET、POST 等)。
路由路径
路由路径可以是字符串、字符串模式或正则表达式。
// 此路由路径将匹配 acd 和 abcd。
app.get("/ab?cd", (req, res) => {
res.send("ab?cd");
});
// 此路由路径将匹配 /abe 和 /abcde。
app.get("/ab(cd)?e", (req, res) => {
res.send("ab(cd)?e");
});
要定义带路由参数的路由,只需使用 :
在路由路径中指定路由参数。
app.get("/users/:userId/books/:bookId", (req, res) => {
res.send(req.params);
});
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
路由方法
路由方法指定一个回调函数或者处理函数,当应用程序接收到与路由路径匹配的请求时,将调用该函数。
app.get("/data", (req, res) => {
res.send("GET request to get data");
});
app.post("/login", (req, res) => {
res.send("POST request to login");
});
路由方法可以有多个回调函数作为参数。对于多个回调函数,重要的是向回调函数提供 next 作为参数,然后在函数体内调用 next(),以便将控制权交给下一个回调函数。 回调函数会根据顺序依次执行。
app.get(
"/example/b",
(req, res, next) => {
console.log("the response will be sent by the next function ...");
next();
},
(req, res) => {
res.send("Hello from B!");
}
);
一个回调函数组可以处理一个路由:
const cb0 = function (req, res, next) {
console.log("CB0");
next();
};
const cb1 = function (req, res, next) {
console.log("CB1");
next();
};
const cb2 = function (req, res) {
res.send("Hello from C!");
};
app.get("/example/c", [cb0, cb1, cb2]);
独立函数和函数数组的组合可以处理一条路由:
const cb0 = function (req, res, next) {
console.log("CB0");
next();
};
const cb1 = function (req, res, next) {
console.log("CB1");
next();
};
app.get(
"/example/d",
[cb0, cb1],
(req, res, next) => {
console.log("the response will be sent by the next function ...");
next();
},
(req, res) => {
res.send("Hello from D!");
}
);
app.all()
是 Express 中的一个特殊的路由方法,它的作用是匹配所有 HTTP 请求方法(GET、POST、PUT、DELETE 等)的指定路径。
// 这个路由会响应 /user 路径的所有 HTTP 方法
// 无论是 GET、POST、PUT、DELETE 都会匹配到这个路由
app.all("/user", (req, res) => {
res.send(`请求方法: ${req.method}, 路径: /user`);
});
// 为某个路径的所有请求添加通用处理逻辑
app.all("/api/*", (req, res, next) => {
console.log("所有 API 请求都会经过这里");
console.log(`请求时间: ${new Date().toISOString()}`);
console.log(`请求路径: ${req.path}`);
next(); // 继续处理后续路由
});
使用 app.route()
可以为路由路径创建可链式调用的路由处理程序:
app
.route("/book")
.get((req, res) => {
res.send("Get a random book");
})
.post((req, res) => {
res.send("Add a book");
})
.put((req, res) => {
res.send("Update the book");
});