MIddleware运行两次

时间:2014-08-01 17:43:55

标签: javascript node.js express

我创建了一个中间件以摆脱我的页面请求,但它似乎运行了两次......

第一次运行没有错误,第二次有错误......

这是我的代码:

app.js文件

app.get('/:slug', buildingController.findBuilding, buildingController.getBuilding);

buildings.js档案

/**
 * Create a Middleware to Find Buildings
 */
exports.findBuilding = function(req, res, next) {
  if (!req.isAuthenticated()) {
    return res.redirect('/login');
  }

  Building.find(
    { "uniqueLink": req.params.slug,
        "$or": [
            { "_creator": req.user.id }
        ]
    }, function(err, building) {
        if (err) {
            return next(err);
        } else {
            if (building.length == 0 || building == null) {
                req.flash('errors', { msg: 'You are not allowed to see this building' });
                res.redirect('/buildings');
                next();
            } else {
                req.building = building[0];
                next();
            }
        }
    }
    );
};


/**
 * GET /:slug
 * Building home page.
 */

exports.getBuilding = function(req, res) {
    var building = req.building;
    res.render('building/home', {
    title: building.name,
    building: building
  });
};

这是控制台输出:

Express server listening on port 3000 in development mode
GET /my-slug 200 359.399 ms - -

好,没有错误但是:

TypeError: Cannot read property 'name' of undefined
[...etc...]

我失败的地方? 在我的页面上一切正常,但我希望没有错误......

我还在学习Node.js。

感谢。

1 个答案:

答案 0 :(得分:2)

 if (building.length == 0 || building == null) {

我认为在这种情况下不应该调用next()