【问题标题】:Socket hang up when using axios.get, but not when using https.get使用 axios.get 时套接字挂起,但使用 https.get 时没有
【发布时间】:2017-04-16 03:23:51
【问题描述】:

据我所知,我正在使用两种不同的方法做同样的事情:

const https = require("https");
const axios = require("axios");

let httpsAgent = new https.Agent({rejectUnauthorized: false});

axios.get(`https://${hostname}:${port}${path}`, {httpsAgent})
    .then((data) => { console.log("axios success: " + data.substr(0, 100)); })
    .catch((error) => { console.log("axios error: " + error); });

let data = "";
https.get({ hostname, path, port, agent: httpsAgent },
    (response) => {
        response.on("data", (chunk) => { data += chunk; });
        response.on("end", () => { console.log("https success: " + data.substr(0, 100)); });
    })
    .on("error", (error) => { console.log("https error: " + error); });

当我运行这段代码时,我得到了 2 个不同的结果:

PS C:\Users\me> .\node\node.exe .\generate-test-data.js
axios error: Error: socket hang up
https success: [{"cool":"data"...

这里发生了什么?我感觉它与异步性有关,但不太确定如何...有人可以提示我这两种行为如何/为什么不同吗?

【问题讨论】:

    标签: javascript node.js https axios node-https


    【解决方案1】:

    啊!

    在 axios 源码中四处挖掘之后,我发现了这个:

    if (!proxy) {
      var proxyEnv = protocol.slice(0, -1) + '_proxy';
      var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
      if (proxyUrl) {
        var parsedProxyUrl = url.parse(proxyUrl);
        proxy = {
          host: parsedProxyUrl.hostname,
          port: parsedProxyUrl.port
        };
    
        if (parsedProxyUrl.auth) {
          var proxyUrlAuth = parsedProxyUrl.auth.split(':');
          proxy.auth = {
            username: proxyUrlAuth[0],
            password: proxyUrlAuth[1]
          };
        }
      }
    }
    

    no_proxy 没有。似乎有一个feature request for this...与此同时,我只需要:

        delete process.env['http_proxy'];
        delete process.env['HTTP_PROXY'];
        delete process.env['https_proxy'];
        delete process.env['HTTPS_PROXY'];
    

    【讨论】:

    • 我需要这个
    • 这是救命稻草 :)
    • 我需要在每次通话之前都包含这个吗?
    • 你能解释更多吗?
    • 我把这个放在每次 axios 调用之前,总是得到套接字挂起错误:/
    【解决方案2】:

    感谢您的领导(和挖掘:)),您确定的代码来自 http 模块,以及它周围;有迹象表明这个问题可以通过其他两种方法来解决

    1. 在 axios 配置中设置 proxy = false,类似于 -
    https.get({ hostname, path, port, proxy:false, agent: httpsAgent },
    
    1. 没有为目标主机设置代理环境变量
    $export NO_PROXY=<host name of targeted URL>
    

    我尝试了上述两种方法,它确实解决了这个问题。干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2019-10-14
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多