Node JS不显示我的数据到模板

Node JS not displaying my data to the template

本文关键字:数据 我的 JS 显示 Node      更新时间:2023-09-26

我正在从Yelp API查询一些数据。Console.log的业务在终端中工作得很好,但是当我在模板中调用相同的变量来渲染时,什么也没有显示。

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});
/*GET Hello World page. */
router.get('/helloworld', function(req, res){
    var first;
    yelp.search({location: "tempe", term: "sandwiches", category_filter: "food"}, function(error, data) {
        var test = JSON.stringify(data); //Changes yelps response to JSON Objects with double quotes
        test = JSON.parse(test); //JSON.parse can now parse correctly after stringify is used.
     //     for(var i = 0; i < 9; i++){
        //    console.log(test['businesses'][i]['name']);
        //  // console.log(test['businesses'][i]);
        // }
        console.log(test['businesses'][0]['name']);
        first = test['businesses'][0]['name'];
    });
    res.render('helloworld', {
            title: 'Hello, World',
            name: first
    });
});
module.exports = router;

yelp.search是异步的。您必须在回调中调用res.render,如:

yelp.search({location: "tempe", term: "sandwiches", category_filter: "food"}, function(error, data) {
    var test = JSON.stringify(data); //Changes yelps response to JSON Objects with double quotes
    test = JSON.parse(test); //JSON.parse can now parse correctly after stringify is used.
 //     for(var i = 0; i < 9; i++){
    //    console.log(test['businesses'][i]['name']);
    //  // console.log(test['businesses'][i]);
    // }
    console.log(test['businesses'][0]['name']);
    first = test['businesses'][0]['name'];
    res.render('helloworld', {
        title: 'Hello, World',
        name: first
    });
});

,否则会在yelp.search返回之前调用

是异步回调。当yelp.search执行时,回调仍未执行,则name未定义。所以你的渲染{name: 'undefined'}。除了@Rodrigo Medeiros的方法,你也可以使用一些模块来解决。例如:qasnycbluebird