【问题标题】:Show the available image in Node.js(when traffic limit exceeded)在 Node.js 中显示可用的图像(超过流量限制时)
【发布时间】:2026-01-13 00:45:01
【问题描述】:

我有一个图片托管服务器,每天流量限制为 600M。

我还可以将图片链接到 Google Drive。当我将图片链接到 Google Drive 时,速度很慢,但没有流量限制。

所以我想让node.js服务器返回可用图片的URL。

我的图片托管域是image.com,我的node.js 服务器的域是node.com

我会像这样在 HTML 中插入图片。

<img src = "http://node.js/image">

node.js 服务器的代码如下。

app.all('/image', function (req, res) {
  if(// should check whether 'http://image.com/' is available now' //)
    res.redirect('http://image.com/image.png');
  else      // The case that image.com is not available
    res.redirect('http://googledrive/imagesourceURL');
});

那么我怎么知道 image.com 现在可用呢?

如果我通过请求真实的图像文件来检查它,它将使用图像托管服务器的流量,所以我认为这不是一个好主意。

我应该在if(//应该检查'http://image.com/'现在是否可用'//)中插入什么

你有什么想法吗?

【问题讨论】:

    标签: node.js http server


    【解决方案1】:

    为了检查是否有可用的 http 资源,您应该执行 http ajax 请求。 在您的情况下,如果状态为 200,您应该重定向到该 URL,否则重定向到另一个 URL。 它会是这样的:

    $.ajax({
      type: "GET",
      url: 'http://image.com/image.png',
      success: function(data, textStatus, jqXHR){
        console.log(textStatus + ": " + jqXHR.status);
            res.redirect('http://image.com/image.png');
    
      },
      error: function(jqXHR, textStatus, errorThrown){
        console.log(textStatus + ": " + jqXHR.status + " " + errorThrown);
        res.redirect('http://googledrive/imagesourceURL');
    
      }
    });
    

    【讨论】:

    • 感谢您的回答 Panciz。我试试看。
    • 注意,代码是异步的,你的方法不会阻塞等待get响应。