渲染JSON

我正在写node.js的应用程序,我有以下代码。

用于从数据库检索主题的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响应)。 我如何做到这一点?

你的代码是不起作用的,但你可以重写它如下:

 // 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 }); }); });