项目说明
该项目只使用 Node.js 标准库实现 HTTP API,适合学习请求解析、路由和响应头,不引入框架。
运行方法
执行 node server.js,服务器监听环境变量 PORT 或默认端口。访问 /health 和 /items,其他路径返回 JSON 404。
验证方式
运行 node --test,测试会在临时端口启动服务器并断言状态码、内容类型和 JSON 结构。还应测试未知路径、非法方法和请求体过大。生产使用需要补充超时、日志、限流和优雅关闭;该项目刻意保持最小以突出 HTTP 基础。
验收清单
完成「使用标准库的 Node.js JSON API」后,按节点或操作步骤逐项自查:准备可复现的本地环境,执行文档中的命令,记录输出与失败信息,并确认权限、空数据和失败恢复路径都有对应证据。
代码示例
import { createServer } from 'node:http';
import { pathToFileURL } from 'node:url';
const items = [{ id: 1, name: 'alpha' }, { id: 2, name: 'beta' }];
export function createApp() {
return createServer((req, res) => {
const send = (status, body) => {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
};
if (req.url === '/health') return send(200, { status: 'ok' });
if (req.url === '/items') return send(200, items);
return send(404, { error: 'not found' });
});
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
createApp().listen(3000, () => console.log('listening on 3000'));
}
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createApp } from './server.mjs';
test('health and items endpoints', async () => {
const server = createApp().listen(0);
const { port } = server.address();
try {
const health = await fetch(`http://127.0.0.1:${port}/health`);
assert.equal(health.status, 200);
assert.deepEqual(await health.json(), { status: 'ok' });
const items = await fetch(`http://127.0.0.1:${port}/items`);
assert.equal(items.status, 200);
assert.equal((await items.json()).length, 2);
const missing = await fetch(`http://127.0.0.1:${port}/nope`);
assert.equal(missing.status, 404);
} finally {
server.close();
}
});
node --test server.test.mjs
node server.mjs
curl -s http://127.0.0.1:3000/health