gpt4 book ai didi

node.js - 在 View 中渲染 JSON

转载 作者:太空宇宙 更新时间:2023-11-03 23:41:48 24 4
gpt4 key购买 nike

我正在用 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 });
});
});

关于node.js - 在 View 中渲染 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22351928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com