【问题标题】:Checking if image exists produces 403 error检查图像是否存在会产生 403 错误
【发布时间】:2019-09-05 11:03:39
【问题描述】:

我有一系列托管图片,但数量和网址可以更改。但是,它们始终遵循相同的递增命名约定。为了存储存在的图像,我遍历可用的图像,直到遇到错误。此时我存储结果并继续操作。

function checkForExistingImage(u, r = [], i = 0){

    var url = u + i;

    $.get(url).done(function() { 
        r.push(url);
        checkForExistingImage(u, r, i + 1);
    }).fail(function(){
        //continue working with the 'r' array
    });
}

但是,这总是会在控制台中导致 403(找不到图像)错误,因为最后检查的图像永远不会存在。

我怎样才能不触发这个错误,或者在需要时抑制它?

【问题讨论】:

  • 403表示禁止,未找到是404。你确定你访问的地方有权限表host吗?
  • 该错误看起来像是您用来找出存在哪些图像的方法的基本部分。您总是可以实现一些返回实际数字的服务器端方法,这样您就不必从客户端探测它们。
  • @Gavin 是的,我可以很好地找到现有的图像,只是当我超过限制时,我会产生错误。
  • @Pointy 遗憾的是,我无法访问后端系统,而只能访问标签管理器
  • 同意Pointy,错误是中断递归的条件。如果您想保留现有逻辑但抑制错误,您可以尝试将对 checkForExistingImage 的调用包装在 try catch 块中。

标签: javascript jquery get


【解决方案1】:

我肯定会以更文明的方式重写它。除了console.log(您可以删除)明确记录的错误之外,此函数不会记录任何错误。

使用它应该更安全,因为它不会以每秒太多的请求轰炸服务器,但如果这不是问题,您可以减少或删除超时。

function Timeout(time) {
  return new Promise(function(resolve) {setTimeout(resolve, time);});
}

async function checkForExistingImages(baseUrl, maxImages, startImage = 0) {
  const results = [];
  // Some sanity check on params
  if(maxImages < startImage) {
    let tmp = maxImages;
    maxImages = startImage + 1;
    startImage = maxImages;
  }
  // from i to max
  for(let i=startImage; i<maxImages; ++i) {
    // Create image URL, change this as needed
    const imageURL = baseUrl + i + ".png";
    // `fetch` does not throw usually, but we wanted to avoid errors in console
    try {
      // Response will have 200/404/403 or something else
      const response = await fetch(imageURL);
      if(response.status == 200) {
        results.push(imageURL);
      }
      else {
        console.info("Image",imageURL,"was removed.");
        // stop loading
        break;
      }
    }
    // complete failure, some major error occured
    catch(e) {
      console.warn("Image",imageURL, "failed to send request!");
      break;
    }
    // If you're getting throttled by the server, use timeout
    await Timeout(200);
  }
  return results;
}

【讨论】:

  • 我不是 100% 确定我理解答案。我的问题是我不知道最大值。它可以是 3、4、9 或 10 个图像。所以我迭代到 max+1,当我得到错误时,我知道我应该停止。但是,错误日志然后,这是我不想要的。
  • @Davy maxImages 可以是 Infinity,我只是在测试答案时包含它。如您所见,在console.info("Image",imageURL,"was removed."); 下,它将中断并且不再加载。但是,上面的代码不会产生任何错误。可以去掉console.log,仅供测试。
猜你喜欢
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多