【问题标题】:Get Fetch Response Status Without Performing A Fetch在不执行 Fetch 的情况下获取 Fetch 响应状态
【发布时间】:2021-02-26 01:31:24
【问题描述】:

有没有办法使用Fetch()XMLHttpRequest() 来获取响应的状态:if(response.status == 200) 或查看响应是否“正常”:if(response.ok),而无需实际获取整个页面。这必须在 JavaScript 中,我正在努力使响应尽可能快。我正在制作一个从另一个网站下载视频的页面。如果可能,我宁愿不使用跨域代理,但它就是这样。

这是我的代码:

var links = ['https://example.com/video1.mp4','https://example.com/video2.mp4','https://example.com/video3.mp4']
links.forEach(function(item, index) {
    var requestplace = new Request('https://cors-anywhere.herokuapp.com/' + item);
    fetch(requestplace).then(function(response) {
        if(response.ok) {
            console.log(`Link #${index + 1}: ${item}`);
        }
        else {
            console.log(`Link #${index + 1}: FAILED`)
        }
});

【问题讨论】:

  • 使用请求method: "HEAD"? ...即fetch(requestplace, { method: 'HEAD'})(实际上,不,把它放在new Request(...., {method: 'HEAD'}
  • @JaromandaX 如果我有支持投票的声誉,我会的。这真的很有帮助。我很感激。如果您想将其作为答案,我会将其标记为“最佳答案”。现在可以在几秒钟内检索视频链接。谢谢。

标签: javascript xmlhttprequest fetch fetch-api


【解决方案1】:

如果你只是想检查一个资源是否存在,使用HEADhttp方法

var links = ['https://example.com/video1.mp4','https://example.com/video2.mp4','https://example.com/video3.mp4']

links.forEach(function(item, index) {
    var requestplace = new Request('https://cors-anywhere.herokuapp.com/' + item, {
       method: 'HEAD'
    });
    fetch(requestplace).then(function(response) {
        if(response.ok) {
            console.log(`Link #${index + 1}: ${item}`);
        }
        else {
            console.log(`Link #${index + 1}: FAILED`)
        }
});

【讨论】:

    猜你喜欢
    • 2012-02-07
    • 2017-01-04
    • 2017-02-07
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2019-01-29
    • 2022-01-21
    • 2017-09-07
    相关资源
    最近更新 更多