Youtube图片api和nodejs https请求的问题

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

我正在尝试使用以下端点获取 YouTube 视频缩略图:

https://i.ytimg.com/vi/<Video-ID>/sddefault.jpg

用我的nodejs代码:

const https = require('https');
https
      .get(
        'https://i.ytimg.com/vi/<Video-ID>/sddefault.jpg',
        {
          agent: new https.Agent({ keepAlive: true, keepAliveMsecs: 15000 }),
        },
        (response) => {
           response.pipe(stream);
           stream.on('finish', () => {
             stream.close();
           });
        }
      )
      .on('error', (err) => {
        console.error('Error downloading file:', err);
      });

但我收到此错误:

connect ETIMEDOUT 10.10.34.35:443
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
  errno: -4039,
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '10.10.34.35',
  port: 443
}

更令我惊讶的是,图像加载到浏览器或邮递员等应用程序中,但不是使用我的代码加载。

也许说我在网络中使用代理会有所帮助,因为错误指示 10.* IP 地址是私有地址。

node.js youtube-api
1个回答
0
投票

是的,问题的发生是因为 Node 没有通过你的代理服务器,并且你的请求超时了。

所以你可以:

1 - 通过代理运行代码

您可以在名为 https-proxy-agent 的节点上使用著名的代理处理程序,您可以通过运行来安装它:

npm install https-proxy-agent

之后您需要在其上添加代理设置:

const https = require("https");
const HttpsProxyAgent = require("https-proxy-agent");

// Define your proxy server address, you can add it as a .env too
const proxy = "http://your-proxy-server.com:8080"; 

// Initialize the https-proxy-agent with the address to the proxy server
const httpsAgent = new HttpsProxyAgent(proxy);

https
      .get(
        'https://i.ytimg.com/vi/<Video-ID>/sddefault.jpg',
        {
          agent: httpsAgent, // Use the proxy agent
          keepAlive: true, 
          keepAliveMsecs: 15000
        },
        (response) => {
           response.pipe(stream);
           stream.on('finish', () => {
             stream.close();
           });
        }
      )
      .on('error', (err) => {
        console.error('Error downloading file:', err);
      });

2 - 断开与代理的连接

© www.soinside.com 2019 - 2024. All rights reserved.