如何在 Node.js 中处理大尺寸(8Mb)的 GET 请求

问题描述 投票:0回答:1

我正在尝试调用这个API https://cwe-api.mitre.org/api/v1/cwe/weakness/all 从node.js服务器,这假设获取8MB的数据,但是我得到这个错误

错误:读取 ECONNRESET 在 TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) { errno: -4077,代码:'ECONNRESET',系统调用:'read' }

我尝试将超时设置为 5 分钟并使用 Axios,但似乎没有任何效果,但是当我使用邮递员发送此请求时,它会在大约 2.5 秒内获取请求,没有任何问题。

 const sendHttpRequest = async (method, url, timeout = null) => {
 const https = require('https');
        return new Promise((resolve, reject) => {
            const agent = new https.Agent({
                keepAlive: true,
                maxSockets: 100
            });
            const options = {
                method: method,
                timeout: timeout,
                agent: agent
            };
            const req = https.request(url, options, (res) => {
                let data = '';
                // Handle incoming data
                res.on('data', (chunk) => {
                    data += chunk;
                });
                // Resolve the promise with the full data once the response ends
                res.on('end', () => {
                    resolve(data);
                });
            });
            req.on('error', (error) => {
                reject(error);
            });
            req.on('timeout', () => {
                reject(new Error('Request timed out'));
            });
            req.end();
        });



 Using Service 

const cweThreatArrayDbURL = 'https://cwe-api.mitre.org/api/v1/cwe/weakness/all';

let apiData = sendHttpRequest("GET", cweThreatArrayDbURL, (30*1000))
    .then((data)=> console.log('response', data))
    .catch(err => console.log(err));
javascript node.js https request backend
1个回答
0
投票

ECONNRESET 错误通常发生在连接被远程服务器意外关闭时,通常是由于大负载、超时或速率限制等问题。要在 Node.js 中处理大型响应(例如 8MB 数据负载),您可能只需要设置更大的超时,如下所示:

const https = require('https');

const options = {
  hostname: 'cwe-api.mitre.org',
  port: 443,
  path: '/api/v1/cwe/weakness/all',
  method: 'GET',
  timeout: 30000, // increase timeout
};

const req = https.request(options, (res) => {
  // Your code
}
© www.soinside.com 2019 - 2024. All rights reserved.