引入
Node.js 常被用于接口和开发服务器。即使之后使用 Express、Koa 或其他框架,也应该先理解请求、响应、状态码和请求体的基本处理过程。
正文
创建最小 HTTP 服务
import { createServer } from 'node:http';
const server = createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
return;
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
});
server.listen(3000, () => {
console.log('Server listening on http://localhost:3000');
});在 package.json 中加入 "type": "module" 后,可以使用上面的 ES Module 写法。
处理请求体
请求体是流,需要分块接收并在结束后解析:
let body = '';
req.setEncoding('utf8');
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});真实服务中还要限制请求体大小,捕获 JSON 解析错误,并校验字段,不能直接信任客户端提交的数据。
服务的基本检查项
引出
手写 http 模块适合理解底层流程,业务项目通常会使用框架处理路由、中间件和参数校验。框架不能替代安全边界,认证、授权和输入校验仍需明确实现。