0

我正在尝试做的事情:如果 url 存在于数据库中,则使用静态页面模板,如果不存在,则显示特定的页面模板。好像也想不通,怎么...

我的 app.js 文件

  app.get('*', function(req, res){
  var currenturl = req.url;
  console.log('URL IS: ' + my_path)
  if (!!db.get(my_path) ) 
    {
      //If it does exist in db
      console.log('Does exist');
      res.render('index', { thetitle: 'Express', title: db.get(currenturl).title, content: db.get(currenturl).content });
    }else{
      //If it doesn't exist in db
      redirect to other sites
      Like: 
      if you go to "/page" it will run this => app.get('/page', routes.index)
      or "/users" will run => app.get('/users', routes.users)
    }
 });
4

2 回答 2

1

您必须创建自己的简单中间件。只要确保你把它放在上面express.router

app.use(function(req, res, next){
  if (!!db.get(my_path)) {
    // render your site from db
  } else {
    // call next() to continue with your normal routes
    next();
  }
});

app.get('/existsInDB', function(req, res) {
  // should be intercepted by the middleware
})

app.get('/page', function(req, res) {
  // should not be intercepted
  res.render('page')
})
于 2012-10-11T13:27:02.843 回答
0

使用快递很容易。您可以使用以下redirect功能:

if (url_exists) res.render('index');
else res.redirect('/foo/bar');
于 2012-10-11T10:05:09.567 回答