在视图中呈现JSON

时间:2014-03-12 12:42:07

标签: node.js express

我正在node.js中编写应用,我有以下代码。

用于从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响应中检索数据)。我如何实现这一目标?

1 个答案:

答案 0 :(得分: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 });
  });
});