Javascript 中间件运行两次
我创建了一个中间件来摆脱我的页面请求,但它似乎运行了两次 第一次运行时没有错误,第二次运行时有错误 这是我的代码: app.js文件Javascript 中间件运行两次,javascript,node.js,express,Javascript,Node.js,Express,我创建了一个中间件来摆脱我的页面请求,但它似乎运行了两次 第一次运行时没有错误,第二次运行时有错误 这是我的代码: app.js文件 app.get('/:slug', buildingController.findBuilding, buildingController.getBuilding); /** * Create a Middleware to Find Buildings */ exports.findBuilding = function(req, res, next) {
app.get('/:slug', buildingController.findBuilding, buildingController.getBuilding);
/**
* 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
});
};
buildings.js文件
app.get('/:slug', buildingController.findBuilding, buildingController.getBuilding);
/**
* 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
谢谢
if (building.length == 0 || building == null) {
我认为在这种情况下不应该调用next()谢谢你的回答,但即使我没有将next()放在那里,我也会调用两次中间件…第二次调用可能是由favicon请求引起的。如果出现这种情况,请在使用中间件之前正确处理它