【发布时间】:2014-11-18 08:37:05
【问题描述】:
我正在尝试创建一个简单的 Web 应用程序,它会触发 http.request 调用,获取数据并将其显示到 html(此处为 ejs)。我能够触发请求、获取数据、对其进行按摩等。但无法将其传递给视图。示例代码如下:
var searchData = [];
router.post('/',requesthandler);
function requesthandler(req,res){
var options = {
host: url,
port: 9999,
path: qstring,
method: 'GET'
};
var reqget = http.request(options,responsehandler);
reqget.end();
console.log('Rendering now:............................ ');
res.render('result',{title: 'Results Returned',searchdata : searchData});
}
function responsehandler(ress) {
console.log('STATUS: ' + ress.statusCode);
ress.on('data', function (chunk) {
output += chunk;
console.log('BODY: ' );
});
/* reqget.write(output); */
ress.on('end',parseresponse);
}
function parseresponse(){
var data = JSON.parse(output);
console.log(data.responseHeader);
// populate searchData here from data object
searchData.push({//some data});
}
function errorhandler(e) {
console.error(e);
}
module.exports = router;
问题是我无法通过 res.render() 将对象 searchData 传递给视图; '现在渲染:......'在 parseresponse() 开始执行之前执行,因此页面显示时没有数据,这似乎与使用回调有关,那么我该如何传递在 parseresponse() 中加载 searchData 后,视图的数据对象。 PS:我可以打印所有控制台语句
【问题讨论】:
标签: json node.js callback httprequest