Kirukato Fu
Kirukato Fu

Reputation: 127

Nodejs https.request head method issue

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?

Upvotes: 0

Views: 437

Answers (2)

Vlad
Vlad

Reputation: 6732

Just wrap it into Promise. E.g:

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

Upvotes: 0

Quentin
Quentin

Reputation: 943537

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>

Upvotes: 1

Related Questions