2013-07-31 117 views
1

img可以將src值重定向到另一個頁面嗎?ExpressJS/NodeJS重定向圖像

考慮,我有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

謝謝

回答

1

是的,可以重定向。最後,它只是一個HTTP服務器和瀏覽器將遵循重定向。

正如在這個問題中提到的那樣:(Is it OK to HTTP redirect images?)你可能不想對很多圖像做這件事。

0

而且你可以設置默認的圖像:

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