how to get data from an api on the server side and pass the data retrieved to pugjs file using expressjs?

501 Views Asked by At

sample code:

// index.pug

p #{polls}

// apiendpoint

http://localhost:8080/api/polls

// routes file (index.js):

Here, how do I make get request to the api, and pass the retrieved result from api(locals) to polls variable while rendering the profile.pug

app.route('/profile')
        .get(isLoggedIn, function (req, res) {

            res.render('profile', {'polls': passvaluehere});
             });

        });
1

There are 1 best solutions below

0
On
You can also use **http**  module like this

var http = require('http');   
var options = {
  host: 'localhost',
  path: '/api/polls',  
  port: '80',  
  method: 'GET'
};


var req = http.request(options, response);
var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
    res.render('profile', {'polls': str});
  });   
req.end();