在url中使用params时出现404页面

404 page when using params in url

本文关键字:404页面 params url      更新时间:2024-04-14

在文件的末尾,我有

app.use(function(req,res){
 res.render('404.jade');
});

这适用于www.website/wongpath,但在我的中

app.get('/path/:id', function(req, res){}

它根本不起作用,而且当您编写一个错误的id(如/path/23187123)时,它会破坏节点服务器。我试过做一些类似的事情:

function checkifexists(){
  var checktime = connection.query('SELECT * FROM table WHERE id = ?', [globalid], function(err, results, rows){
    if(results.length == 0){
      //console.log("0");
      return true;
    }
    return false;
  });
} 
if(checkifexists()){return;}

检查id是否存在,然后取消请求,但这也不起作用。我怎样才能让它与404页面一起工作?

next()不知道如何处理特定请求时,请在路由中使用它。在您的情况下,如果table表上没有记录,它应该将请求传递给与该请求匹配的下一个处理程序,该处理程序可能是您的404

app.get('/path/:id', function(req, res, next){
  connection.query('SELECT * FROM table WHERE id = ?', [globalid], function(err, results, rows){
    if(results.length == 0){
      next();
      return;
    }
    //do something with rows
    //res.render('view.jade')
  });
}

您可以使用next()将请求的处理传递给其他中间件:

app.get('/path/:id', function(req, res, next){
//say if id is too big, don't handle it in this controller
if(req.params.id > 10000) {
  next();
  return;
}
//other code
})
//- so we go further down
//here comes the error display
app.use(function(req,res){
 res.render('404.jade');
});