node.js - 在 node.js 中使用 node-fetch 重用 TCP 连接

标签 node.js http fetch node-fetch

我正在使用此函数调用外部 API

const fetch = require('node-fetch');

fetchdata= async function (result = {}) {
  var start_time = new Date().getTime();

    let response = await fetch('{API endpoint}', {
      method: 'post',
      body: JSON.stringify(result),
      headers: { 'Content-Type': 'application/json' },
      keepalive: true

    });

  console.log(response) 
  var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
  console.log(time)
  return [response.json(), time];
  
}
问题是我不确定每次使用这个函数时 node.js 是否重用了到 API 的 TCP 连接,即使我定义了 keepalive 属性。
重用 TCP 连接可以显着提高响应时间
任何建议将受到欢迎。

最佳答案

https://github.com/node-fetch/node-fetch#custom-agent 中所述

const fetch = require('node-fetch');

const http = require('http');
const https = require('https');

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
const agent = (_parsedURL) => _parsedURL.protocol == 'http:' ? httpAgent : httpsAgent;

const fetchdata = async function (result = {}) {
    var start_time = new Date().getTime();

    let response = await fetch('{API endpoint}', {
        method: 'post',
        body: JSON.stringify(result),
        headers: { 'Content-Type': 'application/json' },
        agent
    });

    console.log(response)
    var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
    console.log(time)
    return [response.json(), time];

}

关于node.js - 在 node.js 中使用 node-fetch 重用 TCP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62500011/

相关文章:

node.js - 如何为自定义过滤器 [Bootstrap、JQuery] 配置 Symfony2 和 Assetic 设置?

reactjs - Fetch 和 setInterval react 钩子(Hook)问题

javascript - 重用与后端服务器的 http 连接 - web fetch API

node.js - 如果值不存在,如何不更新列 sequelize

javascript - 如何终止 npm 子进程

node.js - Vue JS Intellij 设置

java - 如何在 Spring 请求映射中接受多个可选参数,但一次只能接受一个?

Python 代码无法在浏览器上运行

不受支持的浏览器的 HTTP 状态代码

javascript - 获取静态 JSON 文件而不是数组