在 Node 中如何发送请求
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 650
Author 回答者: shfshanyue
如果使用原生 API,可使用 http/https
核心模块
const https = require("https");
https
.get("https://icanhazip.com", (res) => {
console.log("statusCode:", res.statusCode);
console.log("headers:", res.headers);
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
console.log(data);
});
})
.on("error", (e) => {
console.error(e);
});
如果使用第三方库的话,可使用 axios
等。
目前,Node 团队抛弃了核心模块 http/https 从头开发了一个新的 http client,名为 undeci,将有可能成为以后默认的 http client
import { request } from "undici";
const { statusCode, headers, trailers, body } = await request(
"http://localhost:3000/foo",
);
console.log("response received", statusCode);
console.log("headers", headers);
for await (const data of body) {
console.log("data", data);
}