我们正在使用这个接口:https://jsonplaceholder.typicode.com/users和我需要创建一个node.js应用程序,它将从api获得用户列表,并从0创建一个html文件内容,里面有一个关于该用户的表。
我已经用fetch的html/css/js写下了这个任务,它可以工作,但现在我不知道如何用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));
发布于 2019-02-09 20:51:22
我建议您使用最小的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视图中指定超文本标记语言,这将把它转换为超文本标记语言:
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}
https://stackoverflow.com/questions/54610002
复制相似问题