【问题标题】:ExpressJS / NodeJS Redirect ImageExpressJS / NodeJS 重定向图像
【发布时间】:2013-07-31 17:38:28
【问题描述】:

img 的 src 值是否可以重定向到另一个页面?

看来,我有img

<img src='/images/fileName'/>

在 app.js 中

app.get('/images/:fileName', subject.image);

这是我的路线:

exports.image = function(req, res){
    var fileName = req.fileName;
    fs.exists(fileName, function(exists){
        if (exists) {
            res.sendfile(imagePath);
        }else{
            res.redirect('http://gravatar.com/avatar/_some_hash');
        }
    });
}

我的代码有效,但是如果图像不存在,可以使用res.redirect 吗?

谢谢

【问题讨论】:

    标签: html node.js redirect express


    【解决方案1】:

    是的,可以重定向。最后,它只是对 HTTP 服务器的 GET,浏览器将遵循重定向。

    正如这个问题中提到的:(Is it OK to HTTP redirect images?) 你可能不想对很多图像这样做。

    【讨论】:

      【解决方案2】:

      你也可以设置默认图片:

      <img src="/images/fileName" onerror="this.src='/images/default.png'" />
      

      【讨论】:

        猜你喜欢
        • 2020-06-27
        • 2016-12-20
        • 1970-01-01
        • 2017-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多