如果找不到ID
,我想重定向到404页面page routes / users.js
exports.find = function(req, res) {
var id =(req.params.id);
db.getFindById(id,function(err, results){
if (err) return res.send(500, "DB QUERY ERROR");
res.render('usr/details', { finds: results });
});
}
page index.js
app.configure(function(){
app.set('views', __dirname +'/views');
app.set('view engine','jade');
app.use(express.bodyParser({KeepExtensions: true, uploadDir: path.join(__dirname, '/public/img/user-avatar')}));
app.use(express.methodOverride());
app.use(checkDatabase, function(req, res) {res.send(404, "Could not find ")});
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/list-users/finds/:id',checkDatabase);
答案 0 :(得分:0)
您必须在参数列表中添加next
,Express将传递给您的处理程序。它将移动到中间件堆栈中的下一个函数。
然后,如果没有id
匹配,请执行return next()
离开该功能,然后转到将处理您的404的功能。
exports.find = function (req, res, next) {
var id = (req.params.id);
db.getFindById(id, function (err, results) {
// Query failed, note the return to quit the function here.
if (err) return res.send(500, "DB QUERY ERROR");
// Move to next function in middleware steck if result set is empty
if (!results || !results.length) return next();
// We will not get to this call unless the resultset is populated
res.render('usr/details', {
finds: results
});
});
}
然后你可以在use
之后调用一个新函数,该函数将在调用next
的情况下运行。
app.use(user.find, function(req, res) {
res.send(404, "Could not find ")
};
编辑:你可能想要的东西:
<强> index.js 强>
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser({
KeepExtensions: true,
uploadDir: path.join(__dirname, '/public/img/user-avatar')
}));
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/list-users/finds/:id', user.find, function (req, res) {
res.send(404, "Could not find ID");
});
<强>路由/ users.js 强>
exports.find = function (req, res, next) {
var id = (req.params.id);
db.getFindById(id, function (err, results) {
// Query failed, note the return to quit the function here.
if (err) return res.send(500, "DB QUERY ERROR");
// Move to next function in middleware steck if result set is empty
if (!results || !results.length) return next();
// We will not get to this call unless the resultset is populated
res.render('usr/details', {
finds: results
});
});
}