html - 获取 API 数据并使用 nodejs 将其显示在网页上?
问题描述
大家好,我是制作网站的新手,想使用 nodejs。
我正在使用 API 在节点中获取数据:
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
当我在节点中运行它时,它会显示我想要的输出,但是如何使用这些数据并将其显示到网页或用它更改 HTML?我很新,所以请解释一切:<
解决方案
您应该为此使用模板引擎。以下示例使用ejs和express.js
var express = require('express')
var app = express();
app.set("view engine", "ejs");
// This assumes your project has a directory named 'views' in it.
app.set("views", path.join(__dirname, "views"));
app.route('/')
.get(function(req, res){
var templateValues = {
title: 'Sample title',
result_code: 900,
body_text: 'Lorem ipsum dolor sit amet, consectetur...'
}
// Your template file should be in 'your-project-name/views/home.ejs'
res.render("home", templateValues);
}
在你的home.ejs
:
<!doctype html>
<html lang="en">
<head>
<title><%= title %></title>
</head>
<body>
<%= body_text %>
</body>
</html>
这将显示一个 HTML 页面,其标题为Sample title和文本Lorem ipsum dolor sit amet, consectetur ...。templateValues
使用您的变量进行修改,一切就绪。
在此处查看另一个示例
推荐阅读
- python-2.7 - 更新到最新的操作系统版本后无法停止网络服务器
- angularjs - Webpack:仅在一个模块中包含供应商
- sql - SQL JOIN 2 个表,其中包含来自第 3 个表的相似数据和视图
- sql - 具有最大和多重条件的 Epression
- r - 更改数据框的单位和值
- c# - 为什么调试时 Cursor.Position 的值错误?
- c# - 如何以正确的顺序设置 LiveCharts StackedColumns 标签
- visual-studio-code - 如何调试在 linux(远程)下的 QEMU(带有 gdb-server)内运行但使用 windows 主机的 ARM 进程?
- vega-lite - 是否可以在 vega-lite 中注册命名的自定义配色方案
- java - 有没有办法编写 Mockito.when(...) 来覆盖方法的所有重载,即为共享相同方法名称的任何调用返回相同的东西?