Express 路由路径正则详解
在 Express 中,使用正则表达式可以定义更加灵活和复杂的路由。
1. 基本语法
在 Express 中,路由路径可以是一个字符串、字符串模式或者正则表达式。当使用正则表达式时,将其作为路由路径传入 `app.METHOD()` 方法(`METHOD` 可以是 `get`、`post` 等 HTTP 方法)。
const express = require("express");
const app = express();
// 精确匹配路径 `/test`
app.get(/^\/test$/, (req, res) => {
res.send("This route matches the exact path /test");
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
2. 匹配路径中的数字
// `\d+` 表示匹配一个或多个数字
app.get(/^\/articles\/\d+$/, (req, res) => {
res.send("This route matches paths like /articles/123");
});
3. 匹配路径中的字母
`[a-zA-Z]` 表示匹配任意一个大小写字母,`+` 表示匹配一个或多个。
app.get(/^\/books\/[a-zA-Z]+$/, (req, res) => {
res.send("This route matches paths like /books/abc");
});
4. 结合路由参数和正则表达式
可以在路由参数中使用正则表达式,对参数的值进行更精确的限制。
app.get("/products/:productId([0-9a-f]{24})", (req, res) => {
const productId = req.params.productId;
res.send(`Product ID: ${productId}`);
});
5. 匹配多个路径模式
使用正则表达式的分支(`|`)可以匹配多个不同但有相似模式的路径。
app.get(/^\/(about|contact|services)$/, (req, res) => {
const path = req.path;
res.send(`You visited the ${path} page`);
});
6. 匹配中文路径
如果要匹配包含中文的路径,可以使用 Unicode 编码范围来定义正则表达式。
app.get(/^\/中文路径\/[\u4e00-\u9fa5]+$/, (req, res) => {
res.send("This route matches Chinese paths");
});