据我所知,我正在使用两种不同的方法做同样的事情:
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"...
这里发生了什么?我感觉它与异步性有关,但不太确定如何......有人可以给我一个提示,说明这两种行为如何/为什么不同?