Node.js HTTP服务器页面加载异常:需终止进程才显示内容
问题原因及解决方案
核心问题:分块数据解析失败导致响应未结束
你代码里的问题出在request的data事件处理上——第三方API返回的响应可能是分块传输的,data事件会触发多次,每次只返回一部分数据(chunk)。你直接对单个chunk执行JSON.parse(chunk)会抛出语法错误,因为不完整的JSON无法被解析,错误会中断后续代码执行,导致res.end()永远不会被调用,浏览器就会一直处于加载状态,直到进程终止时Node.js才会强制结束响应。
修复方案
方案1:收集所有分块数据后再解析
把所有chunk拼接起来,在end事件里统一解析和处理:
const server = http.createServer((req, res) => { if (req.url == "/") { let rawData = ''; request("https://api.openweathermap.org/data/2.5/weather?q=Bhubaneswar&appid=ee6cc6680b9ce81b7df5332b412c5cff") .on('data', (chunk) => { // 收集所有分块数据 rawData += chunk; }) .on('end', () => { try { const objectData = JSON.parse(rawData); const arrData = [objectData]; const realTimeData = arrData.map((val) => replaceVal(home, val)).join(); res.end(realTimeData); // 直接用end返回响应,无需write } catch (err) { // 处理解析错误,避免服务器崩溃 res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Internal Server Error'); } }) .on('error', (err) => { // 处理请求第三方API的错误 res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Failed to fetch weather data'); }); } else { // 处理其他路由,返回404 res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('404 Not Found'); } });
方案2:使用request的回调式API(更简洁)
request支持直接传入回调函数,自动处理分块拼接:
const server = http.createServer((req, res) => { if (req.url == "/") { request("https://api.openweathermap.org/data/2.5/weather?q=Bhubaneswar&appid=ee6cc6680b9ce81b7df5332b412c5cff", (error, response, body) => { if (error || response.statusCode !== 200) { res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Failed to fetch data'); return; } try { const objectData = JSON.parse(body); const arrData = [objectData]; const realTimeData = arrData.map((val) => replaceVal(home, val)).join(); res.end(realTimeData); } catch (err) { res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Data parse error'); } }); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('404 Not Found'); } });
额外注意事项
- 你之前尝试的
res.end(realTimeData)是正确的写法,res.write+res.end也没问题,但前提是代码能执行到res.end。 - 一定要添加
error事件监听,避免第三方API请求失败时服务器挂起。 - 建议替换已废弃的
request模块,改用axios、node-fetch等现代HTTP客户端,它们的API更直观,也能更好地处理异步逻辑。
内容的提问来源于stack exchange,提问作者Swaraj Behera
相关产品推荐
相关产品推荐

