手写路由
原始 req.url 是带查询串的完整路径(如 /api/user?id=1)。做路由要先把它拆开:用 url.parse 拿到 pathname 与 query,再按 method + pathname 匹配处理函数。
路由的本质就是“if/else 或查找表”。小型服务自己写一张路由表(method + path → handler)足够清晰;路径参数(/users/42)需用 pathname 按 / 拆分解析。再大就该上 Express 框架了。
- url.parse(req.url).pathname:不含查询串的纯路径
- 路由表模式:{ "GET /api/list": handler },查表分发
- 路径参数需自行 split("/") 解析,或直接交给 Express
const http = require('http'); const url = require('url'); const routes = { 'GET /': (req, res) => res.end('首页'), 'GET /api/list': (req, res) => { const { query } = url.parse(req.url, true); // true: 解析成对象 res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ page: query.page || 1 })); }, }; http.createServer((req, res) => { const { pathname } = url.parse(req.url); const key = req.method + ' ' + pathname; const handler = routes[key]; if (handler) return handler(req, res); // 支持 /users/42 这类路径参数 if (/^\/\/users\/\d+$/.test(pathname)) { const id = pathname.split('/')[2]; res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('用户 ID: ' + id); } res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404'); }).listen(3000, () => console.log('路由服务跑在 3000')); // 访问:localhost:3000/api/list?page=3 → {"page":"3"}




