2016-12-30 36 views
0

我有一個節點的JS應用程序,從reddit.com/r/wallpaper獲取圖像。使imgur鏈接具有.png或.jpg結尾的urlJS

您在html頁面上發出請求,它會獲取一張隨機圖像並將其顯示在<img>上。

問題是,有時你imgur網址像http://imgur.com/a/Vtav5不能在<img>顯示,但網址像http://i.imgur.com/vjUeUVj.jpg可以顯示,在Node.js的我怎樣才能獲得url成爲直接圖像網址?繼承人我目前的工作代碼。

app.get('/', function (req, res) { 

    r.getSubreddit(subreddit).getRandomSubmission().then(function(post){ 

     if(post.url.includes(".jpg") || post.url.includes(".png")){ 
      currentUrl = post.url; 
      console.log(currentUrl); 
      res.send(currentUrl); 
      res.end(); 

     } else{ 
      console.log("Not a direct image URL"); 
      console.log(post.url); 
     } 

     }); 
    console.log("Got request"); 
    //res.end(); 


}) 

回答

0

如果無法通過他們的API獲得,最好的辦法是刮擦它,希望你需要刮的鏈接數量不會太大。

var Xray = require('x-ray'); 
var x = Xray(); 

x('http://imgur.com/a/Vtav5', '.post-images .post-image', [{ 
    url: '[email protected]' 
}])(function (err, res) { 
    console.log(res); 
}) 

輸出:

[ { url: 'http://i.imgur.com/vjUeUVj.jpg' } ] 
+0

Ijust遇到了這個惱人的問題,我想你不能改變vairables而服務器啓動和聽力。 – ChrisEthanFox

+0

@ChrisEthanFox你是什麼意思? –

+0

當你運行服務器時,我不認爲任何變量都可以改變,url是一個變量,需要不斷更改爲新的易用的 – ChrisEthanFox

相關問題