为什么我用Node.js开发的Echo Server在localhost上无法正常工作?
Node.js Echo Server 浏览器访问无响应问题解决
问题描述
使用Node.js编写Echo Server,实现读取传入请求的请求体并原样返回,代码如下:
const http = require('http'); http.createServer((request, response) => { let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { response.writeHead(200, { 'Content-Type': 'text/plain' }); body = Buffer.concat(body).toString(); response.write(JSON.stringify(body)); console.log(JSON.stringify(body)); response.end(); }); }).listen(3000, 'localhost');
服务运行后在终端执行curl --location --request POST 'localhost:3000' --header 'Content-Type: text/plain' --data-raw 'Test message'测试,curl和服务端都能正常打印请求体,但浏览器直接访问localhost:3000无响应。
问题原因
- 浏览器直接访问地址时默认发起GET请求,GET请求通常不带请求体,此时服务端接收到的请求体为空,返回内容为空,视觉上呈现为无响应。
- 代码中多余的
JSON.stringify()会将返回的请求体外层包裹双引号,不符合原样返回的需求,空请求体时会返回空双引号"",肉眼更难识别。
修复方案
1. 基础修复(保留原功能,修复返回格式问题)
const http = require('http'); http.createServer((request, response) => { let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { response.writeHead(200, { 'Content-Type': 'text/plain' }); body = Buffer.concat(body).toString(); // 移除JSON.stringify,直接返回原始请求体 response.write(body); console.log(body); response.end(); }); }).listen(3000, 'localhost');
2. 增加GET请求适配(方便浏览器访问时看到提示)
const http = require('http'); http.createServer((request, response) => { // GET请求直接返回提示信息 if (request.method === 'GET') { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('请使用POST请求携带请求体访问本服务'); return; } let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { response.writeHead(200, { 'Content-Type': 'text/plain' }); body = Buffer.concat(body).toString(); response.write(body); console.log(body); response.end(); }); }).listen(3000, 'localhost');
浏览器端POST测试方法
直接在地址栏访问只能发送GET请求,要测试POST功能可以打开浏览器开发者工具(F12)的控制台,执行以下代码:
fetch('http://localhost:3000', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: 'Test message' }).then(res => res.text()).then(data => console.log('服务返回内容:', data))
执行后即可在控制台看到服务返回的请求体内容。
内容的提问来源于stack exchange,提问作者chrysa
相关产品推荐
相关产品推荐

