Node.js RESTful API
核对 REST 架构风格、四种核心 HTTP 动词语义,以及基于 users.json 实现 GET/POST/PUT/DELETE 全流程 RESTful JSON 接口的本地 HTTP 实测。
学完这一章,你能够
- 核对 REST 架构风格、四种核心 HTTP 动词语义,以及基于 users.json 实现 GET/POST/PUT/DELETE 全流程 RESTful JSON 接口的本地 HTTP 实测。
REST 架构风格与 HTTP 核心方法
REST(Representational State Transfer,表述性状态传递)由 Roy Fielding 在 2000 年博士论文中提出,是一组面向分布式超媒体系统的软件架构约束与设计风格,而非单一强制协议标准。RESTful 应用通常直接依托 HTTP、URI 与 JSON(或 XML/HTML)表述资源状态,并利用四个核心 HTTP 方法区分操作意图:`GET` 用于获取资源数据、`POST` 用于新增资源、`PUT` 用于更新或创建指定资源、`DELETE` 用于删除资源。
Web Service 是平台无关、低耦合、自包含的可编程 Web 应用,传统方案常以 XML 体系描述与编排分布式交互,而遵循 REST 原则的 RESTful Web Services 因轻量且直接复用 HTTP 语义成为现代主流。无论是 Java、Python、PHP、Ruby、Perl 还是浏览器端 JavaScript(含 Ajax/Fetch)均可无缝调用,简单只读接口甚至可直接用浏览器访问 GET URI 查看返回的 JSON 文本。
基于 users.json 的 RESTful 接口实现与实测
以本地资源文件 `users.json`(初始包含 `user1` mahesh、`user2` suresh、`user3` ramesh 三条记录)为例,可围绕用户资源设计列表查询、新增、单条详情与删除四个接口。读取全部用户的 `GET /listUsers` 路由读取 `users.json` 并返回 JSON 对象;本站 Node.js v24.22.3 实测 `GET /listUsers` 返回状态码 `200`、包含 `["user1","user2","user3"]` 共 3 条记录且 `user2.name` 为 `suresh`。
新增用户与查询详情分别对应 `addUser` 与路径参数 `/:id`。需要注意:原参考示例为了方便浏览器地址栏演示,曾把新增与删除也写成了 `app.get(...)`,但严格符合 REST 约束的做法应使用 `POST /addUser` 接收 JSON 请求体并持久化写回文件,同时用 `GET /:id` 按编号检索用户(未找到时返回 `404`)。本站实测 `GET /2` 返回 `200` 与 `suresh`(`librarian`)完整对象、`GET /99` 返回 `404`;发送 `POST /addUser` 写入 `user4`(`mohit`)后返回 `201`,键集合更新为 4 项,再次 `GET /4` 准确返回 `mohit`。
更新与删除操作同样应遵守 HTTP 动词语义:使用 `PUT /:id` 更新指定用户的字段,使用 `DELETE /deleteUser` 携带目标 `id` 删除对应条目并持久化。本站实测先执行 `PUT /3` 将 `user3.profession` 更新为 `senior-clerk`(状态码 `200`),再执行 `DELETE /deleteUser` 传入 `{"id":2}` 删除 `user2`(状态码 `200`),最终持久化结果仅保留 `["user1","user3","user4"]` 且确认 `user2` 已移除。
RESTful 用户接口契约表
| 序号 | URI | HTTP 方法 | 发送内容 | 结果 |
|---|---|---|---|---|
| 1 | listUsers | GET | 空 | 返回所有用户 JSON 列表(实测 200,含 user1~user3) |
| 2 | addUser | POST | JSON 字符串 | 新增用户并持久化写回(实测 201,新增 user4) |
| 3 | deleteUser | DELETE | JSON 字符串 | 按指定 id 删除用户(实测 200,移除 user2) |
| 4 | :id | GET | 空 | 返回指定 id 用户详情(实测 /2 为 200,/99 为 404) |
运行基于临时 users.json 的本地 RESTful CRUD 服务实测
import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
const INITIAL_USERS = {
user1: { name: 'mahesh', password: 'password1', profession: 'teacher', id: 1 },
user2: { name: 'suresh', password: 'password2', profession: 'librarian', id: 2 },
user3: { name: 'ramesh', password: 'password3', profession: 'clerk', id: 3 },
};
async function readJsonBody(req) {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
if (chunks.length === 0) return {};
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}
async function main() {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-rest-'));
const dataFile = path.join(tmpDir, 'users.json');
await fs.writeFile(dataFile, JSON.stringify(INITIAL_USERS, null, 2), 'utf8');
const sendJson = (res, status, payload) => {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(payload));
};
const server = http.createServer(async (req, res) => {
const pathname = new URL(req.url || '/', 'http://127.0.0.1').pathname;
const raw = await fs.readFile(dataFile, 'utf8');
const users = JSON.parse(raw);
if (req.method === 'GET' && pathname === '/listUsers') {
return sendJson(res, 200, users);
}
if (req.method === 'POST' && pathname === '/addUser') {
const payload = await readJsonBody(req);
Object.assign(users, payload);
await fs.writeFile(dataFile, JSON.stringify(users, null, 2), 'utf8');
return sendJson(res, 201, users);
}
if (req.method === 'DELETE' && pathname === '/deleteUser') {
const payload = await readJsonBody(req);
const key = `user${payload.id}`;
if (!users[key]) return sendJson(res, 404, { error: 'User not found' });
delete users[key];
await fs.writeFile(dataFile, JSON.stringify(users, null, 2), 'utf8');
return sendJson(res, 200, users);
}
const idMatch = pathname.match(/^\/(\d+)$/);
if (idMatch && req.method === 'GET') {
const user = users[`user${idMatch[1]}`];
if (!user) return sendJson(res, 404, { error: 'User not found' });
return sendJson(res, 200, user);
}
if (idMatch && req.method === 'PUT') {
const key = `user${idMatch[1]}`;
if (!users[key]) return sendJson(res, 404, { error: 'User not found' });
const patch = await readJsonBody(req);
users[key] = { ...users[key], ...patch, id: Number(idMatch[1]) };
await fs.writeFile(dataFile, JSON.stringify(users, null, 2), 'utf8');
return sendJson(res, 200, users[key]);
}
return sendJson(res, 404, { error: 'Route not found' });
});
const cases = [];
try {
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
// Case 1: get_list_users
const listRes = await fetch(`${base}/listUsers`);
const listData = await listRes.json();
const actual1 = {
status: listRes.status,
keys: Object.keys(listData),
count: Object.keys(listData).length,
user2Name: listData.user2.name,
};
const expected1 = {
status: 200,
keys: ['user1', 'user2', 'user3'],
count: 3,
user2Name: 'suresh',
};
cases.push({
name: 'get_list_users',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: get_user_by_id
const u2Res = await fetch(`${base}/2`);
const u2Data = await u2Res.json();
const missRes = await fetch(`${base}/99`);
const missData = await missRes.json();
const actual2 = {
foundStatus: u2Res.status,
user2: u2Data,
missStatus: missRes.status,
missError: missData.error,
};
const expected2 = {
foundStatus: 200,
user2: { name: 'suresh', password: 'password2', profession: 'librarian', id: 2 },
missStatus: 404,
missError: 'User not found',
};
cases.push({
name: 'get_user_by_id',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: post_add_user
const addRes = await fetch(`${base}/addUser`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
user4: { name: 'mohit', password: 'password4', profession: 'teacher', id: 4 },
}),
});
const addData = await addRes.json();
const u4Data = await (await fetch(`${base}/4`)).json();
const actual3 = {
status: addRes.status,
keys: Object.keys(addData),
user4Name: u4Data.name,
user4Id: u4Data.id,
};
const expected3 = {
status: 201,
keys: ['user1', 'user2', 'user3', 'user4'],
user4Name: 'mohit',
user4Id: 4,
};
cases.push({
name: 'post_add_user',
passed: JSON.stringify(actual3) === JSON.stringify(expected3),
expected: expected3,
actual: actual3,
});
// Case 4: delete_user_and_put_update
const putRes = await fetch(`${base}/3`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ profession: 'senior-clerk' }),
});
const putData = await putRes.json();
const delRes = await fetch(`${base}/deleteUser`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: 2 }),
});
const delData = await delRes.json();
const actual4 = {
putStatus: putRes.status,
updatedProfession: putData.profession,
deleteStatus: delRes.status,
remainingKeys: Object.keys(delData),
user2Exists: 'user2' in delData,
};
const expected4 = {
putStatus: 200,
updatedProfession: 'senior-clerk',
deleteStatus: 200,
remainingKeys: ['user1', 'user3', 'user4'],
user2Exists: false,
};
cases.push({
name: 'delete_user_and_put_update',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
await new Promise((resolve) => server.close(resolve));
await fs.rm(tmpDir, { recursive: true, force: true });
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
- 核对 GET /listUsers 返回 3 名初始用户、GET /2 与 /99 返回 200/404、POST /addUser 写入 user4 返回 201,以及 PUT /3 与 DELETE /deleteUser 正确更新并删除 user2。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:2bdd27845aba21426313d455156fd079e54ca6bf228afd1ed12e04d2508cc2d1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:dcb5363031b9c4effdc4b244583310e7a9b7ca50a9a8af49c1a5403969d681dd
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么严格意义上的 RESTful API 不应使用 `GET /addUser` 或 `GET /deleteUser` 来修改和删除数据?
展开参考解答
HTTP 规范约定 `GET` 是安全且幂等的只读方法,可能被浏览器预取、代理缓存或爬虫重复触发;创建与删除资源应分别使用 `POST` 与 `DELETE`(修改使用 `PUT`/`PATCH`),以符合协议语义并避免误改数据。