Creating a simple Node.Js app where need to display data from two APIs, where both APIs returns multiple objects with an ID.
Need to display data from both these APIs on a single page, and somehow need to fetch the data from the two API based on the ID.
API 1 response looks like this:
{
"hikes": [
{
"id": 1,
"active": true,
"name": "Mt. Everest",
},
{
"id": 2,
"active": true,
"name": "K2",
},
{
"id": 3,
"active": true,
"name": "Mt. Kinley",
},
]
}
API 2 response looks like this:
{
"hikes": [
{
"id": 1,
"slots": 50,
"available": 23,
},
{
"id": 2,
"slots": 20,
"available": 1,
},
{
"id": 3,
"slots": 43,
"available": 20,
},
]
}
Need to pull both APIs, fetch the data and render on a page to display "name", "slots", and "available".
This far managed to pull one of the APIs, and pass the data to a rendered index.ejs page, but I am not sure how I should pull the second API and some how fetch the data`s.
My code at the moment looks like this:
var port = process.env.PORT || 3000,
express = require("express"),
request = require("request"),
app = express();
app.set("view engine", "ejs");
var hikes = {
url: "https://api.com/hikes",
headers: {
'Identifier': identifier
}
};
var availability = {
url: "https://api.com/hikes",
headers: {
'Identifier': identifier
}
};
app.get("/", function(req, res){
function callback(error, response, body){
if(!error && response.statusCode == 200){
var data = JSON.parse(body);
res.render("index", {data: data});
})
}
}
request(hikes, callback);
});
app.listen(port, function(){
console.log("Running");
});
In my index.ejs, I for now have created a simple loop to print the names:
<% data["hikes"].forEach(function(hike){ %>
<p><%= hike.name %></p>
<% }) %>
Any ideas on how to solve this?
Thanks!