ExpressJS - URL 构建
Express.js - 动态 URL 构建
Section titled “Express.js - 动态 URL 构建”虽然像 /about 或 /contact 这样的静态路由很有用,但大多数 Web 应用程序需要动态路由来处理可变数据。例如,显示用户资料的路由需要接受用户 ID。Express 通过定义路由参数,可以轻松构建动态 URL。
路由参数(Route parameters)是 URL 的命名片段,以冒号(:)作为前缀。这些片段捕获 URL 中其位置上指定的值。捕获到的值会填充到 req.params 对象中。
示例:单个参数
Section titled “示例:单个参数”这是一个使用 ES6 语法实现动态路由的现代示例:
import express from 'express';
const app = express();const PORT = 3000;
// 定义了一个带有动态 'id' 参数的路由app.get('/users/:id', (req, res) => { // 解构赋值是访问参数的简洁方式 const { id } = req.params; res.send(`You requested the profile for User ID: ${id}`);});
app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`);});要测试这个路由,运行服务器并导航到 http://localhost:3000/users/123。浏览器将显示:
You requested the profile for User ID: 123你可以将 123 替换为任何其他值,响应将动态更新。
示例:多个参数
Section titled “示例:多个参数”你可以在单个路由中定义多个参数。它们都可以在 req.params 对象上获取到。
import express from 'express';
const app = express();const PORT = 3000;
// 带有多个参数的博客文章路由app.get('/posts/:category/:slug', (req, res) => { const { category, slug } = req.params; res.send(`Fetching post with slug "${slug}" in the "${category}" category.`);});
app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`);});要测试这个路由,导航到 http://localhost:3000/posts/tech/modern-javascript-features。服务器将响应:
Fetching post with slug "modern-javascript-features" in the "tech" category.使用正则表达式进行模式匹配路由
Section titled “使用正则表达式进行模式匹配路由”有时你需要为路由参数强制执行特定的格式。你可以在参数名称后面添加括号 () 中的正则表达式来验证其格式。如果正则表达式不匹配,该路由将不会被触发。
示例:验证数字 ID
Section titled “示例:验证数字 ID”假设用户 ID 必须是一串数字。你可以使用正则表达式 ([0-9]+) 来强制执行此规则。
import express from 'express';
const app = express();const PORT = 3000;
// 此路由仅在 'id' 为数字时匹配。app.get('/items/:id([0-9]+)', (req, res) => { const { id } = req.params; res.send(`Item ID: ${id}`);});
// 对于任何其他 '/items/*' 请求的备用处理app.get('/items/*', (req, res) => { res.status(400).send('Invalid Item ID format. ID must be numeric.');});
app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`);});在此示例中:
- 请求
/items/456将由第一个路由处理。 - 请求
/items/abc将不匹配正则表达式,并由第二个更通用的路由处理,返回 400 Bad Request 错误。
处理 404 未找到错误
Section titled “处理 404 未找到错误”如果请求不匹配任何已定义的路由,Express 将自动响应 404 Not Found 错误。最佳实践是定义一个自定义的 404 处理器,以提供用户友好的响应。这可以通过在路由定义最末尾放置一个包罗万象的(catch-all)中间件来完成。
import express from 'express';
const app = express();const PORT = 3000;
// ... 所有其他路由在此处 ...app.get('/', (req, res) => res.send('Welcome!'));
// 包罗万象的 404 处理器app.use((req, res) => { res.status(404).send('Sorry, the page you are looking for does not exist.');});
app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`);});重要提示: Express 按照路由和中间件定义的顺序进行处理。404 处理器必须是添加到应用程序堆栈的最后一个,以确保它只捕获那些未匹配任何其他路由的请求。