如何在Express中呈现http请求的结果?
问题描述:
使用Request和Express,如何呈现我的http请求的结果?
Using Request and Express, how do I access the result of my http request for the purpose of rendering it?
var request = require('request');
var http = require('http');
exports.index = function(req, res){
var apiUrl = 'http://api.bitcoincharts.com/v1/weighted_prices.json';
request(apiUrl, function(err, res, data) {
if (!err && res.statusCode == 200) {
data = JSON.parse(data);
console.log(data);
res.render('index', { data: data });
}
});
};
实际上,我在请求回调中引用的资源是原始响应对象,我想知道如何在不访问请求的情况下从我的exports.index函数调用响应.
As it is, the res I'm referring to within the request callback is the raw response object and I'm wondering how to call the response from my exports.index function without the request being inaccessible.
答
只需重命名参数之一:
// either this:
exports.index = function(req, response) {
...
response.render(...);
};
// or this:
request(apiUrl, function(err, response, data) {
if (!err && response.statusCode == 200) {
data = JSON.parse(data);
console.log(data);
res.render('index', { data: data });
}
};