Node request external API within local get request


Node request external API within local get request



I'm trying provide the response of an external API call when I perform a local GET request but struggling with how to get this to work.



My code at the moment is:


app.get('/', function(req, res){
request.post('http://data.fixer.io/api/latest?access_key=' + apikey +
'&symbols=gbp', function(err, res, body) {
console.log(body)
})
res.render('index')
})



My knowledge and experience with callbacks and async programming is limited, but how do I pass the response of the request POST into the GET request to then pass it to the index?



Thanks!




2 Answers
2



Callbacks can be difficult to understand, and the problem you describe isn't uncommon (it even has a name - Callback Hell). Partly the reason why Node introduced the async / await syntax - here's the equivalent of your code in that style


async


await


app.get('/', async (req, res, next) => {
try {
const uri = `http://data.fixer.io/api/latest?access_key=${apikey}&symbols=gbp`;
const data = await request.post(uri);
return res.render('index', { data }); // or pass whatever you need from `data` into the view
} catch (e) {
return next(e);
}
}



Notice the one big difference? No callbacks and you get all the same benefits of asynchronous code with bonus of writing code in a synchronous style.



You can chain calls in Express, so it's very easy to call an external service within a GET request, e.g.


app.get('/', function(req, res){
request.post('http://data.fixer.io/api/latest?access_key=' + apikey + '&symbols=gbp', function(err, response, body) {
console.log(body)
res.send(body);
})
})



In this case we're sending back the raw response from the POST, it is easy to wrap this in another object, e.g.


res.send( { status: 'ok', post_result: body });





Thanks, got it working, just had to rename the res in the post request to response
– LewMoore
Jun 29 at 9:25






Yes, you're correct!, apologies, I'll update..
– Terry Lennox
Jun 29 at 9:32







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift