我正在解析由远程 API 生成的 JSON 响应。我遍历响应并将所需的字段存储在值中。我从 pug 模板创建我的 homeCard 元素并将值传递给它。这个问题是它只显示 json 响应中的最后一个元素(性感海滩 3)。如何更改我的代码,以便每次通过循环时都创建一个 homecard?
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 响应
您正在为 homecards 数组对象分配相同的值,并且每次迭代也会覆盖相同的数组。您必须在循环外声明 homecards 数组并将对象推送到它。
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;
var homeCards = [];
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;
homeCards.push({
title: title,
link: link,
description: description,
});
console.log(title, description, link);
}
})
.catch(err => {
console.error(err);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句