使用axios.get时套接字挂起,但使用https.get时则不挂起 [英] Socket hang up when using axios.get, but not when using https.get

查看:795
本文介绍了使用axios.get时套接字挂起,但使用https.get时则不挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

推荐答案

ARGH!

在axios来源中挖掘后,我发现了这个:

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

但<$ c没什么$ C> NO_PROXY 。似乎有一个功能请求 ......与此同时,我会必须:

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

这篇关于使用axios.get时套接字挂起,但使用https.get时则不挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆