簡體   English   中英

node.js表示路由數據庫相關

[英]node.js express routing db dependent

我正在嘗試執行的操作:如果db中存在該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)
    }
 });

您必須創建自己的簡單中間件。 只要確保將其放在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')
})

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

if (url_exists) res.render('index');
else res.redirect('/foo/bar');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM