首页 > 解决方案 > 获取 API 数据并使用 nodejs 将其显示在网页上?

问题描述

大家好,我是制作网站的新手,想使用 nodejs。

我正在使用 API 在节点中获取数据:

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  console.log(body);
}); 

当我在节点中运行它时,它会显示我想要的输出,但是如何使用这些数据并将其显示到网页或用它更改 HTML?我很新,所以请解释一切:<

标签: htmlnode.jsapiwebpage

解决方案


您应该为此使用模板引擎。以下示例使用ejsexpress.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使用您的变量进行修改,一切就绪。

在此处查看另一个示例


推荐阅读