2017-01-28 27 views
2

我有一個靜態的HTML頁面,我使用NodeJS來提供該頁面。nodeJS - 修改HTML文件以顯示圖像

我希望能夠從NodeJS動態提供圖像的HTML頁面URL,以便可以顯示這些圖像。

我會怎麼做呢?

+0

轉換的HTML的模板,例如EJS /帕格/小鬍子。 EJS將是最合適的,因爲它基本上是HTML變量。所以你只需要重新命名index.html改爲index.ejs,並用變量替換圖片網址。 –

+0

我的回答有幫助嗎?或者你遇到過這樣的問題嗎? – aguertin

回答

2

使用某種模板引擎。開始的簡單視圖模板引擎稱爲Handlebars。這將允許您爲大部分html頁面動態地創建「佈局」,同時允許您創建「視圖」,這些視圖是將要插入到佈局中的部分html文件。一個例子是一個頁眉和一個頁腳。頁眉和頁腳很可能在整個網站中保持不變,因此您可以將它放在佈局文件中,並且在正文內部可以呈現動態視圖。

把手使用這個符號來呈現的HttpRequest你的HTML文件裏的數據:

HTML

<div id='user-profile-image'> {{profile_image_uri}} </div> 

JS

app.get('/user-by-name', function(req, res) { 

    var options = 
    { 
     "Content-Type" : "application/json", 
     "url" : "blah.com" 
    } 

    // Using the request module 
    request.get(options, function(err, httpResponse, body) { 
     if (err) 
     { 
      console.log(err) 
      return 
     } 
     // First param is your view name 
     // Second param is your json response body which is rendered in 
     // the view using handlebars {{}} 
     res.render('your_view_name_here', JSON.parse(body)) 
    } 
}