HTTP request to obtain HTTP status code, but no content

Viewed 379

I'm using axios to get the http status for URLs:

async function getUrlHttpStatus (url) {
  try {
    const res = await axios({ method: 'get', url })
    return {
      status: res.status,
      statusText: res.statusText
    }
  } catch (err) {
    return {
      status: err.response.status,
      statusText: err.response.statusText
    }
  }
}

This obviously brings back all the content from that URL as well, and if there is a lot, it can be very slow.

Is there a way to make a HTTP request, to get the HTTP status code, without downloading all the content from the URL, so it's quick..?

2 Answers

You can just use the HEAD method, which per definition returns just the Head (i.e. Status code) and no body.

The way you access error is : err.response.data.your_attribute_from_the_server

If the message from the server is in the the error object is in the message attribute Eg : err.response.data.message

async function getUrlHttpStatus (url) {
  try {
    const res = await axios({ method: 'get', url })
    return {
      status: res.status,
      statusText: res.statusText
    }
  } catch (err) {
    return {
      status: err.response.status,
      statusText: err.response.data.message//here replace the message attibute with whatever attribute you've sent from the server
    }
  }
}
Related