Node.js 路由
讲解 Node.js 基于原生 http 模块与 URL/querystring 的路径分发、依赖注入式 server/router/index 模块化架构,以及 Express 动态路由、查询参数、分组与中间件设计。
学完这一章,你能够
- 讲解 Node.js 基于原生 http 模块与 URL/querystring 的路径分发、依赖注入式 server/router/index 模块化架构,以及 Express 动态路由、查询参数、分组与中间件设计。
路由职责与原生 http 基础分发
在 Node.js Web 服务与 RESTful API 中,路由负责将入站请求映射到对应的业务处理器。Node.js 运行时本身不内置完整路由框架,但核心逻辑始终围绕三项动作展开:匹配请求 URL 路径、校验 HTTP 方法(GET、POST、PUT、DELETE 等)以及调用匹配的处理函数。
使用原生 `node:http` 模块即可依据 `req.url` 与 `req.method` 编写简易路由:本站实测回环服务对 `GET /` 返回 `200 Home Page`,对 `GET /about` 返回 `200 About Page`,而对 `POST /about` 或未知路径 `/missing` 均返回 `404 404 Not Found`。更系统的 HTTP 协议语义可结合 HTTP 专题进一步学习。
URL 参数解析与依赖注入式路由模块
一个完整 URL(如 `http://localhost:8888/start?foo=bar&hello=world`)包含主机、路径名与查询字符串。所有请求元数据均挂在回调首参 `request` 上,现代 Node.js 推荐用标准 `new URL(...)` 提取 `pathname` 与 `searchParams`(实测分别得 `'/start'`、`'bar'`、`'world'`),表单体则可配合 `querystring` 模块解析。
先在 `server.js` 的 `onRequest` 中借助 `new URL(request.url, ...)` 提取 `pathname`,使 `/start` 与 `/upload` 等路径能被区分;再单独创建 `router.js` 导出 `route(pathname)` 承担路由分发逻辑,实现服务器监听与业务路由解耦。
为避免在 `server.js` 中硬编码依赖 `router.js`,可采用依赖注入:扩展 `start(route)` 接收路由函数,再由入口文件 `index.js` 调用 `server.start(router.route)` 组装启动。浏览器访问时通常会额外请求 `/favicon.ico`,终端日志可见对应路径记录;本站离线实测依次请求 `/`、`/start?foo=bar` 与 `/upload`,注入的 `route` 函数按序收到 `['/', '/start', '/upload']` 并返回各自响应。
Express 路由体系与高级中间件模式
工程实践中常引入第三方框架 Express(通过 `npm install express` 安装)简化路由声明,它直接提供 `app.get()`、`app.post()` 等方法按路径与 HTTP 动词绑定处理器。
Express 支持动态路由参数与查询参数两类传参:形如 `/users/:id` 或 `/search/:query` 的路径片段会自动提取到 `req.params` 中,而 `?q=...` 形式的查询键值对可通过 `req.query` 直接读取。
对于中大型服务,可通过三类机制保持路由清晰:用前置/后置中间件完成日志记录与鉴权(如校验 `Authorization` 请求头决定放行或返回 `401 Unauthorized`);用 `express.Router()` 将同前缀路由(如 `/users`)分组挂载;同时牢记先定义的路由优先级更高,并挂载四参数错误处理中间件 `(err, req, res, next)` 统一兜底 `500`。本站在离线零依赖回环服务中完整复现并实测了动态参数 `42`、查询参数 `nodejs`、静态优先 `/users/me`、鉴权 401/200 与 500 兜底路径。
运行原生 HTTP 路由、URL 解析、依赖注入路由与 Express 模式回环实验
展开查看收起
import http from 'node:http';
import querystring from 'node:querystring';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(expected) === JSON.stringify(actual),
expected,
actual,
};
}
// Case 1: basic http module URL + method routing
async function testHttpBasicRouting() {
const server = http.createServer((req, res) => {
const { url, method } = req;
if (url === '/' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Home Page');
} else if (url === '/about' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Page');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const rHome = await fetch(`${base}/`);
const rAbout = await fetch(`${base}/about`);
const rPostAbout = await fetch(`${base}/about`, { method: 'POST' });
const rMissing = await fetch(`${base}/missing`);
const expected = {
home: [200, 'Home Page'],
about: [200, 'About Page'],
postAbout: [404, '404 Not Found'],
missing: [404, '404 Not Found'],
};
const actual = {
home: [rHome.status, await rHome.text()],
about: [rAbout.status, await rAbout.text()],
postAbout: [rPostAbout.status, await rPostAbout.text()],
missing: [rMissing.status, await rMissing.text()],
};
return makeCase('http_basic_routing', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 2: URL constructor and querystring parsing
function testUrlAndQueryParsing() {
const myUrl = new URL('http://localhost:8888/start?foo=bar&hello=world');
const qsParsed = querystring.parse('foo=bar&hello=world');
const expected = {
pathname: '/start',
foo: 'bar',
hello: 'world',
qsFoo: 'bar',
qsHello: 'world',
};
const actual = {
pathname: myUrl.pathname,
foo: myUrl.searchParams.get('foo'),
hello: myUrl.searchParams.get('hello'),
qsFoo: qsParsed.foo,
qsHello: qsParsed.hello,
};
return makeCase('url_and_query_parsing', expected, actual);
}
// Case 3: dependency-injected router module (server.start(router.route))
async function testDiRouterArchitecture() {
const routedPaths = [];
function route(pathname) {
routedPaths.push(pathname);
if (pathname === '/start') return 'Handled /start';
if (pathname === '/upload') return 'Handled /upload';
return 'Hello World';
}
function start(routeFn) {
function onRequest(request, response) {
const pathname = new URL(request.url, `http://${request.headers.host}`).pathname;
const body = routeFn(pathname);
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(body);
}
return http.createServer(onRequest);
}
const server = start(route);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const rRoot = await (await fetch(`${base}/`)).text();
const rStart = await (await fetch(`${base}/start?foo=bar`)).text();
const rUpload = await (await fetch(`${base}/upload`)).text();
const expected = {
routedPaths: ['/', '/start', '/upload'],
responses: ['Hello World', 'Handled /start', 'Handled /upload'],
};
const actual = {
routedPaths,
responses: [rRoot, rStart, rUpload],
};
return makeCase('di_router_architecture', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 4: Express-style routing patterns (params, query, router prefix, auth, priority, error handler)
async function testExpressStyleRouterPatterns() {
const logs = [];
function matchPattern(pattern, pathname) {
const pSegs = pattern.split('/').filter(Boolean);
const uSegs = pathname.split('/').filter(Boolean);
if (pSegs.length !== uSegs.length) return null;
const params = {};
for (let i = 0; i < pSegs.length; i += 1) {
if (pSegs[i].startsWith(':')) {
params[pSegs[i].slice(1)] = decodeURIComponent(uSegs[i]);
} else if (pSegs[i] !== uSegs[i]) {
return null;
}
}
return params;
}
const routes = [
{ method: 'GET', pattern: '/', handler: () => ({ status: 200, body: 'Hello, World!' }) },
{ method: 'POST', pattern: '/submit', handler: () => ({ status: 200, body: 'Form submitted!' }) },
{ method: 'GET', pattern: '/users', handler: () => ({ status: 200, body: 'List of users' }) },
{ method: 'GET', pattern: '/users/me', handler: () => ({ status: 200, body: 'Current user (priority)' }) },
{ method: 'GET', pattern: '/users/:id', handler: (req) => ({ status: 200, body: `User ID: ${req.params.id}` }) },
{ method: 'GET', pattern: '/search', handler: (req) => ({ status: 200, body: `Search query: ${req.query.q}` }) },
{
method: 'GET',
pattern: '/admin',
auth: true,
handler: () => ({ status: 200, body: 'Admin page' }),
},
{
method: 'GET',
pattern: '/boom',
handler: () => {
throw new Error('Synthetic route failure');
},
},
];
const server = http.createServer((req, res) => {
const parsed = new URL(req.url, `http://${req.headers.host}`);
logs.push(`${req.method} ${parsed.pathname}`);
try {
for (const r of routes) {
if (r.method !== req.method) continue;
const params = matchPattern(r.pattern, parsed.pathname);
if (params !== null) {
if (r.auth && !req.headers.authorization) {
res.writeHead(401, { 'Content-Type': 'text/plain' });
res.end('Unauthorized');
return;
}
const result = r.handler({
params,
query: Object.fromEntries(parsed.searchParams),
});
res.writeHead(result.status, { 'Content-Type': 'text/plain' });
res.end(result.body);
return;
}
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
} catch {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Something broke!');
}
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const rPost = await fetch(`${base}/submit`, { method: 'POST' });
const rUsers = await fetch(`${base}/users`);
const rPriority = await fetch(`${base}/users/me`);
const rDynamic = await fetch(`${base}/users/42`);
const rQuery = await fetch(`${base}/search?q=nodejs`);
const rNoAuth = await fetch(`${base}/admin`);
const rWithAuth = await fetch(`${base}/admin`, { headers: { Authorization: 'Bearer ok' } });
const rErr = await fetch(`${base}/boom`);
const expected = {
post: [200, 'Form submitted!'],
usersGroup: [200, 'List of users'],
priority: [200, 'Current user (priority)'],
dynamicParam: [200, 'User ID: 42'],
queryParam: [200, 'Search query: nodejs'],
adminDenied: [401, 'Unauthorized'],
adminAllowed: [200, 'Admin page'],
errorHandler: [500, 'Something broke!'],
loggedCount: 8,
};
const actual = {
post: [rPost.status, await rPost.text()],
usersGroup: [rUsers.status, await rUsers.text()],
priority: [rPriority.status, await rPriority.text()],
dynamicParam: [rDynamic.status, await rDynamic.text()],
queryParam: [rQuery.status, await rQuery.text()],
adminDenied: [rNoAuth.status, await rNoAuth.text()],
adminAllowed: [rWithAuth.status, await rWithAuth.text()],
errorHandler: [rErr.status, await rErr.text()],
loggedCount: logs.length,
};
return makeCase('express_style_router_patterns', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
const cases = [
await testHttpBasicRouting(),
testUrlAndQueryParsing(),
await testDiRouterArchitecture(),
await testExpressStyleRouterPatterns(),
];
console.log(JSON.stringify({ version: process.version, cases }));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
通过参数注入路由函数可降低模块耦合度,服务器模块无需绑定特定路由实现,便于在单元测试或不同场景下替换自定义路由处理器。