Node.js原生https模块请求耗时过长问题排查求助
为什么你的Node.js https请求耗时这么久?
兄弟,我看了你这段代码,大概率是这几个关键细节没处理好,导致请求卡了整整一分钟:
没监听错误事件,出问题也不知道
你的代码只处理了请求成功拿到响应的情况,但如果请求过程中出了幺蛾子——比如DNS解析失败、网络波动、服务器拒绝连接,程序根本不会给你任何提示,只会傻等着。这是最常见的“请求卡住”原因!赶紧给请求和响应都加上
error事件监听,这样能立刻知道问题出在哪:const https = require('https'); const req = https.get("https://www.dwitter.net/api/dweets/?limit=1"); // 监听请求阶段的错误 req.on("error", (err) => { console.error('请求出错啦:', err.message); }); req.on("response", function(response) { let body = ""; response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { console.log(body); }); // 还要监听响应阶段的错误 response.on('error', (err) => { console.error('响应处理出错:', err.message); }); });没设置超时,请求会无限等待
Node.js的https.get默认没有超时时间!如果服务器迟迟不响应,你的请求会一直挂着,直到天荒地老。给请求加个超时限制,到点就终止,避免浪费时间:const req = https.get("https://www.dwitter.net/api/dweets/?limit=1"); // 设置10秒超时,时间可以根据需求调整 req.setTimeout(10000, () => { console.log('请求超时了,终止请求'); req.abort(); // 主动终止请求 });可能没处理压缩响应,导致
end事件延迟触发
很多API会返回gzip压缩的响应,如果你直接把二进制chunk拼接成字符串,不仅会得到乱码,还可能因为没正确处理压缩流,导致end事件迟迟不触发。可以检查响应头的Content-Encoding,用Node.js的zlib模块解压:const https = require('https'); const zlib = require('zlib'); const req = https.get("https://www.dwitter.net/api/dweets/?limit=1"); req.on("error", (err) => { console.error('请求出错:', err); }); req.on("response", function(response) { let body = ""; const encoding = response.headers['content-encoding']; let stream = response; // 如果是gzip压缩,就用gunzip解压 if (encoding === 'gzip') { stream = response.pipe(zlib.createGunzip()); } stream.on('data', (chunk) => { body += chunk.toString('utf8'); // 明确指定utf8编码,避免乱码 }); stream.on('end', () => { console.log(body); }); stream.on('error', (err) => { console.error('流处理出错:', err); }); });
建议你先加上错误监听和超时设置,看看是不是这些问题导致的卡顿。如果还是慢,再检查压缩响应的处理情况。
内容的提问来源于stack exchange,提问作者TheGreatRambler
相关产品推荐
相关产品推荐

