使用axios.get时,套接字挂断,但使用https.get时,套接字挂断

Luc*_*cas 2 javascript https node.js node-https axios

据我所知,我正在使用两种不同的方法来做同一件事:

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); });
Run Code Online (Sandbox Code Playgroud)

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

PS C:\Users\me> .\node\node.exe .\generate-test-data.js
axios error: Error: socket hang up
https success: [{"cool":"data"...
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*cas 6

啊!

在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]
      };
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是没有no_proxy。似乎对此有功能要求 ...同时,我将只需要:

    delete process.env['http_proxy'];
    delete process.env['HTTP_PROXY'];
    delete process.env['https_proxy'];
    delete process.env['HTTPS_PROXY'];
Run Code Online (Sandbox Code Playgroud)

  • 我需要在每次通话之前添加此内容吗? (2认同)
  • 我把它放在每次 axios 调用之前,并且总是收到套接字挂起错误:/ (2认同)