import http from 'node:http';
import querystring from 'node:querystring';
function makeCase(name, expected, actual) {
return {
name,
passed: JSON.stringify(expected) === JSON.stringify(actual),
expected,
actual,
};
}
// Case 1: URL properties & URLSearchParams methods
function testUrlAndSearchParamsApi() {
const myUrl = new URL('http://example.com:8080/path?foo=bar&hello=world#section');
const snapshot = {
href: myUrl.href,
origin: myUrl.origin,
protocol: myUrl.protocol,
host: myUrl.host,
hostname: myUrl.hostname,
port: myUrl.port,
pathname: myUrl.pathname,
search: myUrl.search,
searchParamsObj: Object.fromEntries(myUrl.searchParams),
hash: myUrl.hash,
};
const pairs = [];
myUrl.searchParams.forEach((v, k) => pairs.push(`${k}=${v}`));
const initialToString = myUrl.searchParams.toString();
const hasFooBefore = myUrl.searchParams.has('foo');
const getFoo = myUrl.searchParams.get('foo');
myUrl.searchParams.append('newKey', 'newValue');
const afterAppend = myUrl.searchParams.toString();
myUrl.searchParams.set('foo', 'newBar');
const afterSet = myUrl.searchParams.get('foo');
myUrl.searchParams.delete('foo');
const hasFooAfter = myUrl.searchParams.has('foo');
const expected = {
snapshot: {
href: 'http://example.com:8080/path?foo=bar&hello=world#section',
origin: 'http://example.com:8080',
protocol: 'http:',
host: 'example.com:8080',
hostname: 'example.com',
port: '8080',
pathname: '/path',
search: '?foo=bar&hello=world',
searchParamsObj: { foo: 'bar', hello: 'world' },
hash: '#section',
},
pairs: ['foo=bar', 'hello=world'],
initialToString: 'foo=bar&hello=world',
hasFooBefore: true,
getFoo: 'bar',
afterAppend: 'foo=bar&hello=world&newKey=newValue',
afterSet: 'newBar',
hasFooAfter: false,
};
const actual = {
snapshot,
pairs,
initialToString,
hasFooBefore,
getFoo,
afterAppend,
afterSet,
hasFooAfter,
};
return makeCase('url_and_search_params_api', expected, actual);
}
// Case 2: HTTP GET query parsing on 127.0.0.1:0
async function testHttpGetQueryServer() {
const server = http.createServer((req, res) => {
const myUrl = new URL(req.url, `http://${req.headers.host}`);
const name = myUrl.searchParams.get('name') || '未提供';
const siteUrl = myUrl.searchParams.get('url') || '未提供';
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(
JSON.stringify({
pathname: myUrl.pathname,
name,
siteUrl,
summary: `网站名:${name}\n网站 URL:${siteUrl}`,
}),
);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const r1 = await (await fetch(`${base}/user?name=${encodeURIComponent('蓝色天空网')}&url=mbsky.example.com`)).json();
const r2 = await (await fetch(`${base}/user`)).json();
const expected = {
withParams: {
pathname: '/user',
name: '蓝色天空网',
siteUrl: 'mbsky.example.com',
summary: '网站名:蓝色天空网\n网站 URL:mbsky.example.com',
},
missingParams: {
pathname: '/user',
name: '未提供',
siteUrl: '未提供',
summary: '网站名:未提供\n网站 URL:未提供',
},
};
const actual = { withParams: r1, missingParams: r2 };
return makeCase('http_get_query_server', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 3: HTTP POST application/x-www-form-urlencoded + 405 method check + HTML form
async function testHttpPostUrlencoded() {
const postHTML = '<form method="post"><input name="name"><input name="url"></form>';
const server = http.createServer((req, res) => {
if (req.url === '/only-post') {
if (req.method !== 'POST') {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Only POST requests are supported.');
return;
}
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const parsed = querystring.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(parsed));
});
return;
}
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const parsed = querystring.parse(body);
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (parsed.name && parsed.url) {
res.end(`网站名:${parsed.name}<br>网站 URL:${parsed.url}`);
} else {
res.end(postHTML);
}
});
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const r405 = await fetch(`${base}/only-post`);
const rPost = await fetch(`${base}/only-post`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'name=example&age=25',
});
const rFormEmpty = await fetch(`${base}/form`);
const rFormSubmit = await fetch(`${base}/form`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'name=BlueSky&url=mbsky.example.com',
});
const expected = {
methodNotAllowed: [405, 'Only POST requests are supported.'],
postParsed: { name: 'example', age: '25' },
formEmptyHasFormTag: true,
formSubmitted: '网站名:BlueSky<br>网站 URL:mbsky.example.com',
};
const actual = {
methodNotAllowed: [r405.status, await r405.text()],
postParsed: await rPost.json(),
formEmptyHasFormTag: (await rFormEmpty.text()).includes('<form method="post">'),
formSubmitted: await rFormSubmit.text(),
};
return makeCase('http_post_urlencoded_and_405', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
// Case 4: HTTP POST JSON body parsing + 400 invalid JSON handling
async function testHttpPostJsonBody() {
const server = http.createServer((req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
try {
const parsed = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: true, received: parsed }));
} catch {
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ ok: false, error: 'Invalid JSON' }));
}
});
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const base = `http://127.0.0.1:${port}`;
try {
const rOk = await fetch(`${base}/json`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user: 'Alice', score: 98 }),
});
const rBad = await fetch(`${base}/json`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{invalid-json',
});
const expected = {
validStatus: 200,
validBody: { ok: true, received: { user: 'Alice', score: 98 } },
invalidStatus: 400,
invalidBody: { ok: false, error: 'Invalid JSON' },
};
const actual = {
validStatus: rOk.status,
validBody: await rOk.json(),
invalidStatus: rBad.status,
invalidBody: await rBad.json(),
};
return makeCase('http_post_json_body', expected, actual);
} finally {
await new Promise((resolve) => server.close(resolve));
}
}
const cases = [
testUrlAndSearchParamsApi(),
await testHttpGetQueryServer(),
await testHttpPostUrlencoded(),
await testHttpPostJsonBody(),
];
console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-node-js-get-post-lab/explore-node-js-get-post.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-node-js-get-post.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1061.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip