【发布时间】:2019-10-15 17:37:27
【问题描述】:
我正在解析远程 API 生成的 JSON 响应。我遍历响应并将所需的字段存储在值中。我从 pug 模板创建我的 homeCard 元素并将值传递给它。这个问题是它只显示 json 响应中的最后一个元素(性感海滩 3)。如何更改我的代码,以便每次通过循环时都会创建一个家庭卡?
const axios = require('axios');
axios({
url: "https://api-v3.igdb.com/games",
method: 'GET',
headers: {
'Accept': 'application/json',
'user-key': 'user-key'
},
data: "fields name,summary,url,popularity;sort popularity desc;limit 4;"
})
.then(response => {
/* GET home page. */
router.get('/', (req, res, next) => {
res.render('index', { pageId: 'index',
title: 'Homepage',
cards: homeCards
});
});
//Iterate through the JSON array
let r = response.data;
for (i=0; i<r.length; ++i){
//create homecards with
var title = r[i].name;
var description = r[i].summary;
var link = r[i].url;
var homeCards = [
{
title: title,
link: link,
description: description,
},
{
title: title,
link: link,
description: description,
},
{
title: title,
link: link,
description: description,
},
{
title: title,
link: link,
description: description,
},
]
console.log(title, description, link);
}
})
.catch(err => {
console.error(err);
});
这是 JSON 响应
【问题讨论】:
-
"这里是 JSON 响应" 请以文本形式发布代码、标记、JSON 等数据等。作为文本,而不是作为 图片的文字。为什么:meta.stackoverflow.com/q/285551/157247 另外,发布的 JSON 无效(缺少前导
[),但我认为您只是截断了图片...