如何从服务器端的api获取数据并使用expressjs将检索到的数据传递给pugjs文件?

时间:2017-01-04 15:22:16

标签: node.js express pugjs

示例代码:

// index.pug

p #{polls}

// apiendpoint

http://localhost:8080/api/polls

//路由文件(index.js):

在这里,我如何向api发出get请求,并在呈现profile.pug

的同时将检索到的结果从api(locals)传递给polls变量
app.route('/profile')
        .get(isLoggedIn, function (req, res) {

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

        });

1 个答案:

答案 0 :(得分:2)

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();