nodejs有问题,https.request返回
const checkStatus = await https
.request(
{
method: 'HEAD',
host: 'host',
path: 'path',
},
(response) => {
const { statusCode } = response;
// idk
},
)
.on('error', (e) => {
if (e) {
throw new Error();
}
})
.end();
我可以以某种方式在 checkStatus 变量中返回 statusCode 吗?
await
一个承诺,但
https.request
不会返回承诺。要么:
new Promise
或中
(async function () {
const url = "https://jsonplaceholder.typicode.com/todos/1";
const response = await axios.head(url);
console.log(response.status);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script>
Promise
中即可。例如:
import https from "https";
const response = await new Promise((resolve, reject) => {
const agent = new https.Agent({ keepAlive: false });
https
.request("https://example.com", { method: "HEAD", agent: agent }, (res) => {
resolve(res);
})
.on("error", (err) => {
reject(err);
})
.end();
});
console.log(response.statusCode);
console.log(response.headers);