Node.js Web 模块
核对 Web 服务器职责、四层 Web 应用架构,以及使用 Node.js 内置 http 模块实现静态文件服务、路径穿越防护与 HTTP 客户端流式接收的离线实测行为。
学完这一章,你能够
- 核对 Web 服务器职责、四层 Web 应用架构,以及使用 Node.js 内置 http 模块实现静态文件服务、路径穿越防护与 HTTP 客户端流式接收的离线实测行为。
Web 服务器与四层应用架构
Web 服务器是驻留在网络主机上的服务程序,核心职责是基于 HTTP 协议、HTML 文档格式与 URL 规范向浏览器等客户端提供信息浏览服务。除静态资源分发外,常见 Web 服务器通常配合服务端脚本语言(如 PHP、Python、Ruby 或 Node.js)访问数据库并动态生成响应,业界广泛使用的经典 Web 服务器包括 Apache、Nginx 与 IIS。
典型 Web 应用由四个逻辑层次协同构成:Client(客户端,通常是浏览器,通过 HTTP 协议发起资源请求)、Server(服务端,即接收请求并回传响应数据的 Web 服务器)、Business(业务层,负责应用逻辑运算、数据库交互与外部程序调用)以及 Data(数据层,一般由关系型或文档型数据库承载持久化存储)。原页此处配有一张架构示意图,因未缓存仅保留锚点记录。
使用 http 模块搭建静态 Web 服务器
Node.js 通过内置 `node:http`(CommonJS 写法为 `require('http')`)同时提供 HTTP 服务端与客户端能力。搭建基础静态文件服务器时,需组合 `http.createServer`、`fs` 与路径解析逻辑:收到请求后解析 URL 路径,从本地目录读取 `index.html` 等目标文件,命中时写回状态码 `200` 与 `Content-Type: text/html; charset=utf-8` 响应头,缺失时返回 `404` 并调用 `response.end()` 结束响应。
启动服务并访问 `/index.html` 后,服务端日志会记录收到的路径并输出 HTML 正文。工程实践中切忌像最小示例那样直接 `pathname.substr(1)` 拼接读取磁盘,否则可能遭遇目录穿越攻击。本站 Node.js v24.22.3 本地实测在 `127.0.0.1` 临时端口启动静态服务:请求 `/index.html` 返回 `200`(正文含 `<h1>Web Server Ready</h1>` 且日志记下 `/index.html`),请求 `/missing.html` 返回 `404 Not Found`,而针对 `/%2e%2e/%2e%2e/secret.txt` 的越界请求在 `path.resolve` 根目录前缀校验下被拦截并返回 `403 Forbidden`。原页浏览器展示截图未缓存,已登记待核对。
使用 http 模块创建 Web 客户端与响应接收
Node.js 既可作为服务端也可充当 HTTP 客户端:使用 `http.request(options, callback)` 指定 `host`、`port`、`path` 后,通过监听响应流 `data` 事件拼接分片并在 `end` 事件中取得完整正文,最后务必调用 `req.end()` 真正发出请求;在现代 Node.js v24 中还可直接使用内置全局 `fetch()`。本站实测同一静态页面分别经由 `http.request` 流式接收与 `fetch()` 拉取,两者均返回状态码 `200`、正文完全一致(UTF-8 共 `175` 字节,标题为 `BlueSky Web Lab`)。
运行本地 http 静态文件服务器、路径穿越拦截与客户端流式拉取实验
import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
function httpRequest(port, rawPath) {
return new Promise((resolve, reject) => {
const req = http.request(
{ host: '127.0.0.1', port, path: rawPath, method: 'GET' },
(res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
resolve({
status: res.statusCode,
contentType: res.headers['content-type'] || '',
body,
});
});
},
);
req.on('error', reject);
req.end();
});
}
async function main() {
const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-web-module-'));
const htmlDoc = [
'<!DOCTYPE html>',
'<html lang="zh-CN">',
'<head><meta charset="utf-8"><title>BlueSky Web Lab</title></head>',
'<body><h1>Web Server Ready</h1><p>Static HTML response</p></body>',
'</html>',
].join('\n');
await fs.writeFile(path.join(tmpRoot, 'index.html'), htmlDoc, 'utf8');
const requestLog = [];
const server = http.createServer(async (req, res) => {
const rawPathPart = (req.url || '/').split('?')[0];
const rawPathname = decodeURIComponent(rawPathPart);
requestLog.push(rawPathname);
const rel = rawPathname.replace(/^\/+/, '') || 'index.html';
const resolvedRoot = path.resolve(tmpRoot);
const target = path.resolve(resolvedRoot, rel);
if (!target.startsWith(resolvedRoot + path.sep) && target !== resolvedRoot) {
res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Forbidden');
return;
}
try {
const content = await fs.readFile(target, 'utf8');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(content);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Not Found');
}
});
const cases = [];
try {
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
// Case 1: static_file_server_200
const okRes = await httpRequest(port, '/index.html');
const actual1 = {
status: okRes.status,
contentType: okRes.contentType,
hasHeading: okRes.body.includes('<h1>Web Server Ready</h1>'),
loggedPath: requestLog[0],
};
const expected1 = {
status: 200,
contentType: 'text/html; charset=utf-8',
hasHeading: true,
loggedPath: '/index.html',
};
cases.push({
name: 'static_file_server_200',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: missing_file_returns_404
const missRes = await httpRequest(port, '/missing.html');
const actual2 = { status: missRes.status, body: missRes.body };
const expected2 = { status: 404, body: 'Not Found' };
cases.push({
name: 'missing_file_returns_404',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: path_traversal_guard_403
const travRes = await httpRequest(port, '/%2e%2e/%2e%2e/secret.txt');
const actual3 = { status: travRes.status, body: travRes.body };
const expected3 = { status: 403, body: 'Forbidden' };
cases.push({
name: 'path_traversal_guard_403',
passed: JSON.stringify(actual3) === JSON.stringify(expected3),
expected: expected3,
actual: actual3,
});
// Case 4: http_client_stream_and_fetch
const streamRes = await httpRequest(port, '/index.html');
const fetchRes = await fetch(`http://127.0.0.1:${port}/index.html`);
const fetchText = await fetchRes.text();
const titleMatch = fetchText.match(/<title>([^<]+)<\/title>/);
const actual4 = {
httpRequestStatus: streamRes.status,
fetchStatus: fetchRes.status,
sameBody: streamRes.body === fetchText,
byteLength: Buffer.byteLength(fetchText, 'utf8'),
title: titleMatch ? titleMatch[1] : null,
};
const expected4 = {
httpRequestStatus: 200,
fetchStatus: 200,
sameBody: true,
byteLength: Buffer.byteLength(htmlDoc, 'utf8'),
title: 'BlueSky Web Lab',
};
cases.push({
name: 'http_client_stream_and_fetch',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
await new Promise((resolve) => server.close(resolve));
await fs.rm(tmpRoot, { recursive: true, force: true });
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
- 核对 /index.html 返回 200 与 175 字节正文、/missing.html 返回 404、/%2e%2e/%2e%2e/secret.txt 返回 403,以及 http.request 与 fetch 接收结果完全一致。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
当前源码 SHA256:ebad5033716365b8bc28fc765bae7359552441ffa1c314b7f057be518c4633e9
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Node.js v24.22.3 本地运行环境。
ZIP SHA256:bd24322498e49da513a4de485caa29019c384148577afe164c8225b4ca8b7d97
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Node.js 静态文件服务器中,为什么不能直接用 `fs.readFile(pathname.substr(1))` 读取请求路径?应如何防护?
展开参考解答
直接截取 URL 路径拼接文件系统会允许客户端利用 `../` 或编码后的 `%2e%2e/` 访问根目录以外的敏感文件;应先解码并对目标路径做 `path.resolve(root, rel)`,严格校验结果位于根目录前缀之内,越界时直接返回 `403`。