【问题标题】:Create Node.js app that gets data from api and creates table in html file with that data创建从 api 获取数据并使用该数据在 html 文件中创建表的 Node.js 应用程序
【发布时间】:2019-02-09 19:37:57
【问题描述】:

我们正在使用这个 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));

【问题讨论】:

  • 我能得到一些建议吗?
  • 既然你已经有了一个javascript文件,为什么不直接使用ajax呢?
  • 很抱歉,我被告知不要使用快递。感谢您的回复
  • 功课围绕着 axios 和 node.js。这就是为什么((
  • 您应该能够创建服务器并使用节点本地语言的路由。其余的真的很相似。我确定有很多关于它的文档:)

标签: node.js json npm axios


【解决方案1】:

我建议您使用最小的 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})
  })
}

您将在views/index.pug 的 pug 视图中指定 HTML,这会将其转换为 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}

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2018-03-19
    • 2020-07-18
    • 2014-06-25
    • 2015-11-11
    相关资源
    最近更新 更多