【问题标题】:Unable to send data in response to the view in nodejs无法响应nodejs中的视图发送数据
【发布时间】: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


    【解决方案1】:

    全局定义 res 变量:

    var res;      
    function requesthandler(req,resObj){
        res = resObj;//set it to the resObj
    }
    

    将 res.render 包装在这样的函数中:

    function renderPage(){
        res.render('result',{title: 'Results Returned',searchdata : searchData});
    }
    

    然后在 parseresponse 函数中这样做:

    function parseresponse(){
        var data = JSON.parse(output);
        searchData.push({some data});
        renderPage();
    }
    

    希望这能解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-16
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多