据我所知,我正在使用两种不同的方法做同样的事情:
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"...
这里发生了什么?我有一种感觉它与异步性有关,但不太确定如何......有人可以给我一个关于这两种行为如何/为什么不同的提示吗?
最佳答案
啊!
在 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'];
关于javascript - 套接字在使用 axios.get 时挂断,但在使用 https.get 时不挂断,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43433380/