【问题标题】:I've built an express js app. When I load a page I always have to refresh for varibles to display?我已经构建了一个 express js 应用程序。当我加载页面时,我总是必须刷新才能显示变量?
【发布时间】:2016-03-31 03:20:13
【问题描述】:

希望你能帮助我。我一直在寻找答案,但一直没有找到。

我在 Express.js 中构建了一个应用程序,它有一个简单的 jam 形式。如果数据库已连接,则应显示“是”。

页面将加载并且不显示任何内容。如果我然后 Ctrl-R 或刷新我期望的值将正确显示。

如何让它自动显示而不刷新..?

干杯,谢谢,

马特

index.jade

p Connected to DB?:
    if locals.connected
    p= connected

index.js(通过 app.js -> routes.js -> index.js 路由到

Var connected;    
function listCollections() {
      mongoose.connection.on('open', function () {
        connected = "Yes";
});
}


exports.init = function(req, res, next){
  listCollections();
  res.render('./index', {
     connected:connected
   });
}
};

Routes.js

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.set('X-Auth-Required', 'true');
  req.session.returnUrl = req.originalUrl;
  res.redirect('/login/');
}

function ensureAdmin(req, res, next) {
  if (req.user.canPlayRoleOf('admin')) {
    return next();
  }
  res.redirect('/');
}

function ensureAccount(req, res, next) {
  if (req.user.canPlayRoleOf('account')) {
    if (req.app.config.requireAccountVerification) {
      if (req.user.roles.account.isVerified !== 'yes' && !/^\/account\/verification\//.test(req.url)) {
        return res.redirect('/account/verification/');
      }
    }
    return next();
  }
  res.redirect('/');
}
exports = module.exports = function(app, passport) {
  app.all('/*', ensureAuthenticated);
  app.all('/*', ensureAccount);
  //product
  app.get('/', require('./views/index').init);
  app.post('/', require('./views/index').init);


};

【问题讨论】:

  • 你能显示你的路由配置吗?
  • 嗨,是的,我会把它添加到帖子中。

标签: javascript jquery node.js express


【解决方案1】:

由于它是异步的,因此页面会在您建立连接之前呈现。你应该这样做。

       function listCollections(callback) {
            mongoose.connection.on('open', function () {
                callback("Yes"); // render callback gets invoke after connection
            });
        }


        exports.init = function(req, res, next){
            listCollections(function(connected){ // passing render as callback
                res.render('./index', {
                    connected:connected
                });
            });
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2016-11-21
    • 2018-07-07
    相关资源
    最近更新 更多