I'm writing an application in node.js, using data from https://swapi.co/. One of my functionalities requires to check whether specified planet exists in my db, when it doesn't, api should download planet's data from swapi, but somehow I cannot retrieve data about specified by name planet, I can only get data with format provided with this link: https://swapi.co/api/planets/?format=json
Method's code:
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);
}
});
});
This is JSON.
Planets stored in results
.
So results it is array of objects, now you can go through all the elements of the array using for
or in
.
You can manipulate however you want, loops, filters, etc.
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])
}
});