Socket hang up when using axios.get, but not when

2020-07-17 15:55发布

问题:

To the best of my knowledge, I am doing the same thing using 2 different approaches:

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); });

When I run this code, i get 2 different outcomes:

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

What is going on here? I have a feeling it has to do with asynchronicity, but not quite sure how... Can somebody give me a hint as to how/why these 2 behaviors are different?

回答1:

ARGH!

After digging around in the axios source, I found this:

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]
      };
    }
  }
}

But nothing for no_proxy. Seems there is a feature request for this... In the meantime, i will just have to:

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