I am trying to show the output of an API request call on a web page. However I am unsure how to structure the code so that the function (which sends a GET to retrieve data from an API) is called before the GET which is then routed and rendered to display a web page.
var express = require('express');
var request = require('request');
var router = express.Router();
var options = {
'method': 'GET',
'url': 'https://bpdts-test-app.herokuapp.com/city/London/users',
'headers': {
'accept': 'application/json'
}};
/* GET home page. */
router.get('/', function(req, res, next) {
getLondonUsers();
res.render('index', { title: this.londonUsers});
});
async function getLondonUsers(){
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
this.londonUsers = response.body;
});
}
module.exports = router;
Jade file displaying the page:
extends layout
block content
h1= 'Here are all the users within a 50 mile radius of London:'
p #{londonUsers}