发送函数的响应以expressjs的方式进行路由

我试图从api返回JSON数据回我的路线在一个快速服务器上。 我对nodejs如何处理这种操作有点困惑。 我有一个函数和路由在同一个文件中,路由工作,因为我得到了返回的视图,我想在控制台中的数据。 路线和方法如下所示:

function getData() { request(url, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Show the HTML for the Google homepage. return response.body; }; }); }; /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'About', data: getData() }); }); 

我想从getData()的数据中获取路由的响应。 我认为这样做,但它只会打印数据到控制台,我看不到问题。

由于http请求的asynchronous性质,这是不可能的。 你将不得不重新调整它有一个callback。

 function getData(callback) { request(url, function (error, response, body) { if (error) { return callback(error); } if (response.statusCode == 200) { console.log(body) // Show the HTML for the Google homepage. //return response.body; callback(null, response.body); } else { callback(response.statusCode); } }); }; /* GET home page. */ router.get('/', function(req, res, next) { getData(function (err, data) { if (err) { return next(err); } res.render('index', { title: 'About', data: data }); }); });