我有一个静态 HTML 页面,我使用 NodeJS 来提供该页面。
我希望能够从 NodeJS 动态提供图像的 HTML 页面 URL,以便可以显示这些图像。
我该怎么做?
最佳答案
使用某种模板引擎。一个易于启动的 View 模板引擎称为 Handlebars 。这将允许您为大部分保持不变的 html 页面动态创建“布局”,同时允许您创建“ View ”,它们是将插入到布局中的部分 html 文件。页眉和页脚就是一个例子。页眉和页脚很可能在整个网站中保持不变,因此您可以将其放入布局文件中,而正文内部是可以呈现动态 View 的地方。
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))
}
}
关于html - nodeJS - 修改 HTML 文件以显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905276/