如果找不到ID,我想重定向到404页面

时间:2014-02-25 11:36:56

标签: node.js express

如果找不到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);

1 个答案:

答案 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
        });
    });
}