[英]Can't filter JSON-like thing
我正在使用https://swapi.co/中的數據在node.js中編寫應用程序。 我的功能之一是要檢查數據庫中是否存在指定的行星,當它不存在時,api應該從swapi下載行星的數據,但是不知何故我無法檢索名稱為Planet所指定的數據,我只能獲取具有以下格式的數據:此鏈接: https://swapi.co/api/planets/?format=json
: https://swapi.co/api/planets/?format=json
方法的代碼:
router.route('/Planets')
.post(function (req, res) {
var planet = new Planet(req.body);
//validate planet.name here
Planet.find({name: planet.name}, function (err, planet) {
if (err) {
res.status(500).send(err);
}
if (planet == '') {
console.log("action: planet not found");
request.get(
'https://swapi.co/api/planets/?format=json',
{json: true},
function (error, response, body) {
console.log(body);
}
);
// planet.save();
res.status(201).send(planet);
} else {
res.status(201).send(planet);
}
})
})
.get(function (req, res) {
Planet.find(function (err, planets) {
if (err) {
res.status(500).send(err);
} else {
res.json(planets);
}
});
});
這是JSON。 行星存放在results
。 因此,結果是對象數組,現在您可以使用for
或in
遍歷數組的所有元素。
您可以根據需要進行操作,循環,過濾器等。
fetch("https://swapi.co/api/planets/?format=json") .then(res => res.json()) .then(res => { console.log(res); // Array of planets stored in res.results for (let i=0; i<res.results.length; i++) { console.log("Name:", res.results[i].name, "Data:", res.results[i]) } });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.