Node.js内置HTTP服务器处理POST请求JSON解析报错解决(无Express)
解决Node.js内置HTTP服务器接收JSON POST请求报错问题
问题根源
"Unexpected end of JSON" 报错通常是因为请求体未完整接收,或者客户端请求头配置不正确,导致服务器解析JSON时内容不完整或为空。
修复步骤
1. 客户端请求必须配置正确的请求头
发送POST请求时,必须指定Content-Type: application/json,同时设置Content-Length告知服务器请求体的字节长度,避免服务器提前结束接收。示例客户端代码:
const http = require('http'); const postData = JSON.stringify({ content: 'Text' }); const options = { hostname: 'localhost', port: 3000, path: '/', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; const req = http.request(options, (res) => { res.on('data', (chunk) => { console.log('响应内容:', chunk.toString()); }); }); req.write(postData); req.end();
2. 服务器端完善解析逻辑与错误处理
原代码缺少错误捕获和请求完整性校验,修改后的服务器代码:
const http = require('http'); const server = http.createServer((req, res) => { if (req.method !== 'POST') { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('仅支持POST请求'); } let chunks = []; req.on('data', (chunk) => chunks.push(chunk)); req.on('end', () => { res.setHeader('Content-Type', 'text/plain'); try { const rawData = Buffer.concat(chunks).toString('utf8'); // 校验请求体是否为空 if (!rawData.trim()) throw new Error('请求体为空'); const parsedData = JSON.parse(rawData); res.end(parsedData.content || '未找到content字段'); } catch (err) { res.writeHead(400); res.end(`解析失败: ${err.message}`); } }); // 捕获请求过程中的错误,避免服务器崩溃 req.on('error', (err) => { console.error('请求异常:', err); res.writeHead(500); res.end('服务器内部错误'); }); }); server.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
3. 核心注意事项
Content-Length头是关键:服务器依赖这个值判断请求体是否接收完整,缺失可能导致end事件提前触发,拿到不完整的JSON字符串。- 错误捕获不可少:用
try/catch包裹JSON解析逻辑,避免解析失败导致服务器进程崩溃。 - 监听请求错误:处理网络中断等异常情况,保证服务器稳定性。
内容的提问来源于stack exchange,提问作者stckvrw
相关产品推荐
相关产品推荐

