首页 > 解决方案 > 创建从 api 获取数据并使用该数据在 html 文件中创建表的 Node.js 应用程序

问题描述

我们正在使用这个 API: https : //jsonplaceholder.typicode.com/users 我需要创建一个 node.js 应用程序,它将从 api 获取用户列表并从 0 创建一个 html 文件内容,其中包含一个表那个用户。

我已经用 html/css/js 和 fetch 写下了这个任务,它可以工作,现在我不知道如何用 node.js 来完成它。目前,我只有以下代码:

const axios = require('axios');
const url = 'https://jsonplaceholder.typicode.com/posts';
axios.get(url)
.then(function (response) {
    //console.log(response.data);
    let arr = [];
    arr = response.data;
    fillTheTable(arr);
  })
.catch((error) => console.log(error));

标签: node.jsjsonnpmaxios

解决方案


我建议您使用最小的 MVC Express 应用程序:

app.js您启动服务器时:

var express = require('express');
var app = express();
var index = require('../controllers/index');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.get('/', function (req, res) { // index url of your web app. Will call to index controller
  index
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

controlles/index.js您指定主 url 的逻辑时(获取 API 的数据并将其呈现到视图以转换为 HTML):

const axios = require('axios');

const asyncUtil = fn =>
    function asyncUtilWrap (req, res, next, ...args) {
        const fnReturn = fn(req, res, next, ...args)
        return Promise.resolve(fnReturn).catch(next)
    }

module.exports = {
  index: asyncUtil(async (req, res, next) => {
      let users = await axios(url)
      res.render('index', {users})
  })
}

您将在 pug 视图中指定 HTML views/index.pug,这会将其转换为 HTML:

table
  thead
    tr
      th Id
      th Name
      th Username

  tbody
    each user in users // iterate through users json
      tr
        td #{user.id}
        td #{user.name}
        td #{user.username}

推荐阅读