我正在使用此函数调用外部 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/