2014-03-12 95 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。 –