从routes.js传递变量到我的.ejs页面 [英] passing a variable from routes.js to my .ejs page
问题描述
我正在尝试从数据库中传递查询
I am trying to pass a query from my database
var aboutUser = connection.query("SELECT about FROM users WHERE username = ?", req.user, function(err, rows) {});`
和我想像这样通过
res.render('profile.ejs', {
user: req.user,
about: aboutUser // get the user out of session and pass to template
});`
我已经在我的ejs页面上尝试过
I have tried this on my ejs page
<%= about%>
但未定义,有人可以在这里帮助我
but about is not defined can someone please help me out here
推荐答案
connection.query
的返回值不是查询的结果。而是一个排序对象,允许高级使用查询。结果是传递给您提供的回调的第二个参数。在您的示例中,其名为行
。这样做的原因是因为查询是异步的。查询完成后将调用回调。
The return value of connection.query
is not the result of the query. Rather it's a sequencing object that allows advanced use of the query. The result is the second argument passed to the callback you are providing. In your example it's named rows
. The reason for this is because the query is asynchronous. The callback is invoked when the query completes.
没有完美的答案方法,因为正确执行此操作取决于应用程序的结构。但是,作为临时解决方案,它应该可以正常工作:
There's no perfect way of answering your question because doing this correctly depends on how your application is structured. However, as a temporary fix this should work:
var aboutUser = connection.query(选择关于FROM用户的用户名= ?,req.user,函数(错误,行){
res.render('profile.ejs',{
用户:req.user,
关于:行
});
});
从长远来看,您不想这样做,但至少可以使您满意开始。
You don't want to do this in the long run for a variety of reasons but at least this should get you started.
这篇关于从routes.js传递变量到我的.ejs页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!