[英]how do I send data from one app.js file to index.ejs file in Routes
[英]How do I pass and use a variable from app.js to index.ejs
為什么以我在下面嘗試的方式將變量從 app.js 傳遞到 index.ejs 不起作用,我該如何正確地做到這一點? 我正在使用 Mongoose 和 EJS 並嘗試使用console.log()
將數據寫入網頁上的數據庫中,而不是在運行提示中。
app.get('/', function(req, res, next){
Review.find(function (err, doc) { // doc is an array
if (err) return console.error(err);
var docOne = doc[0]; // saving data of db in variable
res.render('index', {title: "Website"}, {docOne: docOne});
})
});
<p>Name: <%= docOne %> </p>
doc = Review.findOne();
app.get('/', function(req, res, next){
Review.find(function (err, doc) { // doc is an array
if (err) return console.error(err);
res.render('index', {title: "Website"});
})
});
<p>Name: <%= doc %> </p>
對於情況 (1),我在刷新頁面后收到錯誤,說docOne is not defined
,在情況 (2) 中,使用全局變量而不是顯示集合的所有內容,我得到Name: [object Object]
。 我確實在渲染后使用console.log(doc)
驗證了集合是否有信息。
我嘗試了一些相關的帖子和修復(總結了上面顯示的那些),但沒有一個成功。
就像評論所暗示的那樣。 我錯誤地傳遞,應該通過res.render('index', {title: "Website", docOne});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.