0

Have a problem with nodejs, https.request returns <http.ClientRequest>

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

Can i somehow return statusCode instead <http.ClientRequest> inside checkStatus variable?

Kirukato Fu
  • 117
  • 1
  • 1
  • 7

1 Answers1

1

You can only usefully await a promise but https.request does not return a promise.

Either:

  • Wrap it in a new Promise or
  • Replace it with a library which supports promises by default (such as Axios or 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>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335