http 模块是 Node Web 的原生能力。本文手写一个带路由的 Web 服务(Express 之前先懂原理),结尾附路由服务小案例。
一、createServer 基础
const http = require('http');
const server = http.createServer((req, res) => {
// req:请求对象(method/url/headers)
// res:响应对象(writeHead/end)
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
res.end('Hello');
});
server.listen(3000, () => console.log('listening :3000'));
二、请求对象 req
req.method // GET / POST
req.url // /api/user?id=1
req.headers // 请求头
req.socket.remoteAddress // 客户端 IP
三、响应对象 res
res.writeHead(200, {'Content-Type': 'application/json'});
res.write('部分'); // 可多次
res.end('结束'); // 必须 end
// 或一步:res.end(json)
四、GET/POST 参数解析
// GET:解析查询串
const { URL } = require('url');
const u = new URL(req.url, `http://${req.headers.host}`);
u.searchParams.get('id');
// POST:收集请求体
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const data = JSON.parse(body); // 或 querystring.parse(body)
});
五、简单路由分发
const routes = {
'GET /': (req, res) => res.end('首页'),
'GET /about': (req, res) => res.end('关于'),
'POST /api': (req, res) => res.end('接收'),
};
const server = http.createServer((req, res) => {
const key = `${req.method} ${req.url.split('?')[0]}`;
const handler = routes[key];
if (handler) return handler(req, res);
res.writeHead(404);
res.end('Not Found');
});
六、静态文件服务(要点)
const fs = require('fs');
const path = require('path');
function serveStatic(req, res, root) {
let file = path.join(root, req.url);
// ⚠️ 防路径穿越:normalize 后必须还在 root 内
if (!path.resolve(file).startsWith(path.resolve(root))) {
res.writeHead(403); return res.end('Forbidden');
}
if (fs.existsSync(file)) {
const ext = path.extname(file);
const types = {'.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css'};
res.writeHead(200, {'Content-Type': types[ext] || 'application/octet-stream'});
fs.createReadStream(file).pipe(res);
} else {
res.writeHead(404); res.end('Not Found');
}
}
七、注意
- res.end() 必调;Content-Type 别忘(中文要 charset);
- POST body 要监听 data/end 两个事件收集;
- 生产用 Nginx 反代(Node 只处理动态);
- 手写路由了解原理即可,项目用 Express/Koa。
八、小案例:手写 RESTful 路由服务
const http = require('http');
const { URL } = require('url');
const users = [{id: 1, name: 'Tom'}];
const server = http.createServer((req, res) => {
const u = new URL(req.url, `http://${req.headers.host}`);
const route = `${req.method} ${u.pathname}`;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
const send = (code, data) => { res.writeHead(code); res.end(JSON.stringify(data)); };
if (route === 'GET /api/users') {
send(200, users);
} else if (route === 'GET /api/users/' + u.pathname.split('/')[3]) {
const id = +u.pathname.split('/')[3];
const user = users.find(x => x.id === id);
user ? send(200, user) : send(404, {error: 'not found'});
} else if (route === 'POST /api/users') {
let body = '';
req.on('data', c => body += c);
req.on('end', () => {
const u2 = JSON.parse(body);
users.push({id: users.length + 1, ...u2});
send(201, users[users.length - 1]);
});
} else {
send(404, {error: 'not found'});
}
});
server.listen(3000, () => console.log('API: http://localhost:3000/api/users'));
GET 列表/详情 + POST 创建 + JSON 响应 + 404 —— 不用框架手写 REST API,原理一清二楚(下一节 Express 就是它的封装)。
九、总结
createServer 回调收 req/res;GET 用 URL 解析、POST 监听 data/end;路由 = method+path 匹配表;静态服务防路径穿越;原理会了再上框架。