2012-10-11 49 views
0

我在做什么: 如果url中存在使用静态页面模板的数据库,如果没有,则显示特定的页面模板。似乎无法弄清楚,怎么过......node.js express routing db dependent

我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) 
    } 
}); 

回答

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') 
}) 
+0

这正是我期待的!谢谢! – dasmikko

0

使用express容易。您可以使用redirect功能:

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

我不确定这就是我正在寻找的东西。我已经更新了我的OP帖子,希望能让自己更清楚。 – dasmikko