1

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}
Marcooz2007
  • 335
  • 1
  • 9
  • **Warning**: [request](https://www.npmjs.com/package/request) is deprecated. You should switch to another module. (You might want to pick one that uses Promises out of the box) – Quentin May 29 '20 at 15:15
  • (Don't use `this` in functions that aren't part of an object.) If you stick with your current callback library, you'd do it by passing a callback into `getLondonUsers` and having it call that callback with the data. Usage: `getLondonUsers(londonUsers => res.render("index", {title: londonUsers});` Accept the callback as a parameter and call that parameter from the `request` completion callback. – T.J. Crowder May 29 '20 at 15:17
  • @T.J. Crowder I have just tried your suggestion but for some reason the page doesn't render - could you please elaborate a little on hw to use the callback as a parameter? This is all new to me – Marcooz2007 May 29 '20 at 15:24
  • You'd remove the `async` (since you're not using `await`) and: `function getLondonUsers(callback) { request(options, (error, response) => { if (error) { /*...handle / report error, DON'T just rethrow it...*/ } else { callback(response.body); } }` – T.J. Crowder May 29 '20 at 15:43
  • I'm getting an error for not defining 'callback' have I written the below code correctly? Thanks so much for your help! router.get('/', function (req, res, next) { function getLondonUsers(callback) { request(options, (error, response) => { if (error) { /*...handle / report error, DON'T just rethrow it...*/ } else { callback(response.body); } }) londonUsers => res.render("index", {title: londonUsers}); } }); – Marcooz2007 May 29 '20 at 15:52

0 Answers0