2014-03-12 96 views
1

我在node.js中编写应用程序,我有以下代码。呈现视图中的JSON

从DB

检索主题API
allTopics = function (req, res) { 
    db.Topic.all({limit: 10}).success(function (topics) { 
    res.send(topics) 
    }); 
}; 

路线为主题的指数

app.get('/topics', function (req, res){ 
    res.render('topics/index.ejs',{ topics : allTopics }) 
    }); 

是上面的代码正确的路线?

另外,我有index.ejs文件,我想列出所有主题(即从json响应中检索数据)。我如何实现这一目标?

回答

2

你的代码,是不会工作,但你可以按如下方式重写:

// notice how I am passing a callback rather than req/res 
allTopics = function (callback) { 
    db.Topic.all({limit: 10}).success(function (topics) { 
    callback(topics); 
    }); 
}; 


// call allTopics and render inside the callback when allTopics() 
// has finished. I renamed "allTopics" to "theData" in the callback 
// just to make it clear one is the data one is the function. 
app.get('/topics', function (req, res){ 
    allTopics(function(theData) { 
    res.render('topics/index.ejs',{ topics : theData }); 
    }); 
}); 
+0

谢谢@Hector。 –