获取API数据并使用Node.js将其显示在网页上?

时间:2018-08-14 00:57:00

标签: html node.js api webpage

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

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

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

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

1 个答案:

答案 0 :(得分:0)

您应该为此使用模板引擎。以下示例将 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页面,其标题为示例标题,文本为 Lorem ipsum dolor sitant,很安全... 。用您的变量修改templateValues,一切就绪。

here

中签出另一个示例
相关问题