Categories
JavaScript Answers

How to get error status code with Node http get?

Spread the love

To get error status code with Node http get, we can listen for the error event.

For instance, we write

const https = require("https");

const request = https.get("https://example.com", (response) => {
  console.log(response.statusCode);
});

request.on("error", (error) => {
  console.error(error.status);
});

to call get to make a request to https://example.com.

We get the statusCode for a normal response with response.statusCode in the callback.

If there’s an error, then the error event callback is called and we get the status from error.status.

We listen for the error event with request.on`.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.