简体   繁体   English

HTTP请求获取HTTP状态码,但是没有内容

[英]HTTP request to obtain HTTP status code, but no content

I'm using axios to get the http status for URLs:我正在使用axios来获取 URL 的 http 状态:

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.这显然也带回了 URL 的所有内容,如果有很多,它可能会很慢。

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..?有没有办法发出 HTTP 请求,获得 HTTP 状态码,而无需从 URL 下载所有内容,所以很快。

You can just use the HEAD method, which per definition returns just the Head (ie Status code) and no body.您可以只使用HEAD方法,每个定义只返回 Head(即状态代码)而不返回正文。

The way you access error is: err.response.data.your_attribute_from_the_server您访问错误的方式是: 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如果来自服务器的消息在错误 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
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM