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

Node JS not displaying my data to the template

我正在查询 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 等等。