Nodejs https.request头方法问题

问题描述 投票:0回答:2

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 吗?

javascript node.js https
2个回答
1
投票
您只能有用

await

 一个承诺,但 
https.request
 不会返回承诺。

要么:

  • 将其包裹在new Promise
  • 替换为默认支持promise的库(如axios或node-fetch)

(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>


0
投票
只需将其包裹到

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);
    
© www.soinside.com 2019 - 2024. All rights reserved.