vdenotaris
vdenotaris

Reputation: 13637

Render API response body content with node.js

Working with Node.js, I wrote a router implementation as follows:

router.get('/fileshare', oauth2.required, (req, res, next) => {
  var apiResponse = null;

  // Consume GCP API
  const queryObject = {
    project: config.get('GCLOUD_PROJECT'),
    prefix: 'msf-test-fs'
  };
  request.get({
    url: 'https://www.googleapis.com/storage/v1/b',
    qs: queryObject,
    auth: {
      'bearer': req.user.token
    }
  }, function(err, res) {
    if (err) {
      self.callback(err, null);
      return;
    }
    console.log(res.body); // Has content
    apiResponse = res.body
  });
  // Render content

  // I WOULD LIKE TO HAVE HERE THE API RESPONSE BODY!!!
  console.log(apiResponse); // Is null
  res.render('pages/list', { }); // <<-- response body here as param
});

It basically invoke an API endpoint and retrieve an response body. I would now like to pass the API response body to render a webpage.

However, the apiResponse is null while invoking console.log(apiResponse);.

How could I fix it?

Upvotes: 0

Views: 1081

Answers (1)

barnski
barnski

Reputation: 1732

The callback invoked by request is called asynchronously after res.render. You need to move res.render to the callback and stop shadowing res variable.

router.get('/fileshare', oauth2.required, (req, res, next) => {

  // Consume GCP API
  const queryObject = {
    project: config.get('GCLOUD_PROJECT'),
    prefix: 'msf-test-fs'
  };
  request.get({
    url: 'https://www.googleapis.com/storage/v1/b',
    qs: queryObject,
    auth: {
      'bearer': req.user.token
    }
  }, function(err, response) {
    if (err) {
      self.callback(err, null);
      return;
    }
    console.log(response.body); // Has content

    // Render content

    console.log(response.body); 
    res.render('pages/list', JSON.parse(response.body)); // <<-- response body here as param
  });
});

Upvotes: 2

Related Questions