简体   繁体   English

如何仅从 XMLHttpRequest 获取响应标头

[英]How to get only response headers from XMLHttpRequest

是否可以在不下载文件数据的情况下仅从XMLHttpRequest获取响应标头?

If the server you are making the request to supports the method, it sounds like what you want is to make an HTTP HEAD request.如果您发出请求的服务器支持该方法,听起来您想要的是发出 HTTP HEAD 请求。 See the HTTP spec .请参阅HTTP 规范

For example compare the output from curl -v -X GET https://github.com and curl -v -X HEAD https://github.com .例如比较curl -v -X GET https://github.comcurl -v -X HEAD https://github.com

Also see HTTP HEAD Request in Javascript/Ajax?另请参阅Javascript/Ajax 中的 HTTP HEAD 请求?

Firstly, the answer from John fixes this issue but it got downvoted because it didn't have enough of an explanation.首先,John 的回答解决了这个问题,但因为没有足够的解释而被否决。

So here is the fix with an explanation as well as an extra bit that you can add as well.因此,这里是带有解释的修复程序以及您可以添加的额外位。

Client side solution is as follows (I am using the status code as the example):客户端解决方案如下(我以状态码为例):

function checkStatus(url) {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest(); 
    request.open('HEAD', url, true)

    request.onreadystatechange = () => {
      if (request.readyState >= 2) {
        resolve(request.status)
        request.abort()
      }
    }

    request.onerror = (e) => {
      reject(e)
    }

    request.send()
  })
}

The reason why this works is for two reasons.这有两个原因。

Firstly we are passing HEAD in as the method instead of GET this should be enough on its own, but if you want to do more, you can move onto the second reason.首先,我们将HEAD作为方法而不是GET传入,这本身就足够了,但是如果您想做更多,则可以转到第二个原因。

The second reason this works is because of the readyState states.这样做的第二个原因是因为readyState状态。

0 = UNSENT
1 = OPENED
2 = HEADERS_RECEIVED
3 = LOADING
4 = DONE

At state 2 the headers are ready to be viewed.在状态2 ,标题已准备好查看。 This means you can then return whatever you need and/or abort the rest of the request preventing any further data being downloaded.这意味着您可以返回您需要的任何内容和/或中止请求的其余部分,以防止下载任何进一步的数据。

Worth noting you can also do this with request.onprogress at stage 3 .值得注意的是,您还可以在第3阶段使用request.onprogress执行此操作。

See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState and https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods for more details.有关更多详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyStatehttps://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

Using JavaScript (as specified in the question) simply use a head request via AJAX:使用 JavaScript(如问题中所述)只需通过 AJAX 使用head请求:

var xhr = new XMLHttpRequest();
var method = 'head';
var url = 'https://www.example.com/';
xhr.open(method,url,true);
xhr.send(null);

xhr.onreadystatechange = function()
{
 if (xhr.readyState === 4)
 {
  console.log(xhr.getAllResponseHeaders())
 }
}

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

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