nodeJS - 修改HTML文件以显示图像

时间:2017-01-28 00:48:15

标签: html node.js web

我有一个静态HTML页面,我正在使用NodeJS来提供该页面。

我希望能够从NodeJS动态提供图像的HTML页面URL,以便显示这些图像。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

使用某种模板引擎。一个简单的视图模板引擎称为Handlebars。这将允许您动态创建"布局"对于大部分保持不变的html页面,同时允许您创建" views"这些是将插入布局的部分html文件。一个例子是页眉和页脚。页眉和页脚很可能在整个网站中保持不变,因此您可以将其放在布局文件中,而正文内部则可以呈现动态视图。

Handlebars使用此表示法在html文件中呈现httpRequest数据:

<强> 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)) 
    }
}