简体   繁体   English

MySQL表一个全局变量,ejs和nodejs

[英]MySQL table a global variable, ejs and nodejs

I'm trying to figure out how I can make a global variable that can grab from a mysql table. 我试图弄清楚如何制作一个可以从mysql表中获取的全局变量。

app.get('*', function(req, res, next){
  res.locals.user = req.user || null;
  res.locals.mobs = db.query('SELECT * FROM mobs', function(err, rows){
    var rowLength = rows.length;
    for (var i = 0; i < rowLength; i++) {
      var mobs = rows[i];
    }
  });

The mobs ones is what I am trying to do. 小怪们就是我想做的。 using <%= mobs[0].name %> produces aa cant get from undefined. 使用<%= mobs[0].name %>会导致无法定义。

I think you need this 我想你需要这个

db.query('SELECT * FROM mobs', function(err, rows){
      res.locals.mobs = rows
  });

if you want pass the data to template try this 如果您想将数据传递给模板,请尝试此

db.query('SELECT * FROM mobs', function(err, rows){
               res.render('view.ejs',{mob:rows})
          });

I found an answer! 我找到了答案! I am not sure if it is the most efficient, but here it is: 我不确定这是否是最有效的,但是这里是:

app.use(function(req, res, next) {
  res.locals.errors = null;
  // Mob Database
  db.query('SELECT * FROM mobs', function(err, rows){
    req.mobs = rows;
    res.locals.mobs = req.mobs;
  });
  next();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM