Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialCamille Sébastien Niessen
2,653 PointsHow can I get data from multiple API's in a route using NodeJS with react and request?
Hi everyone,
I'm working with NodeJS for a while now, and started using data from API's for a application that I'm building. In one of my routes I'm performing a request to get data out of the Treehouse API. Now I also want to add a (or more) other API request to get data. I've been looking on the internet but couldn't find a solution! I hope someone can help me. This is de code:
routes/api.js var express = require('express'); var router = express.Router(); var request = require('request');
var username = "camillesbastienniessen";
router.get('/', function(req, res) {
request('http://teamtreehouse.com/' + username + '.json', function(error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
res.locals.data = data;
res.locals.session = req.session;
res.render('api/index');
}
});
});
module.exports = router;
This is the extra API I want to get data from:
request('http://api.openweathermap.org/data/2.5/weather?q=' + req.session.hometown + ',uk&APPID=b0149af4c0540497fa854049d3b550ad&lang=nl', function (error, response, body) { if (!error && response.statusCode == 200) { var weatherData = JSON.parse(body); } });
How can I load the data in the same view as the data from the Treehouse API? Hope you van help me!
1 Answer
Thomas Nilsen
14,957 PointsHere is one way you can make multiple requests, using the Node request module.
var request = require("request");
var weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=b0149af4c0540497fa854049d3b550ad&lang=no';
var treehouseURL = 'http://teamtreehouse.com/thomasnilsen.json'
var result = [];
function getTreehouseData(error, response, body) {
if(!error && response.statusCode === 200) {
result.push({
treehouse: body
});
}
request(weatherURL, getWeatherData);
}
function getWeatherData(error, response, body) {
if(!error && response.statusCode === 200) {
result[0].weather = body;
}
console.log(result);
}
//MAIN CALL
request(treehouseURL, getTreehouseData);
Camille Sébastien Niessen
2,653 PointsThanks so much, I'm going to try if it works!
Camille Sébastien Niessen
2,653 PointsCamille Sébastien Niessen
2,653 PointsSorry, de code krijg ik niet helemaal goed hier weergeven in codeblock ..