我正在尝试使用通配符get函数,根据需要呈现视图(我使用jQuery来调用这些视图)。
这是我正在尝试的代码:
app.get('/*.ejs', function(req, res){ // Actions View if (req.xhr) { if ('actions') { res.render('actions'); } else if ('profile') { res.render('profile'); } } else { res.redirect('/game'); } });我知道这没有任何作用,并且它总是会使我的行为看起来,也许你不能以这种方式开始。 我的问题是:我是不是错了? 我宁愿不为每个我想要的视图创建不同的获取函数。
I am trying to have a wildcard get function that renders a view based on what is needed (I am using jQuery to call these views).
Here is the code I am trying:
app.get('/*.ejs', function(req, res){ // Actions View if (req.xhr) { if ('actions') { res.render('actions'); } else if ('profile') { res.render('profile'); } } else { res.redirect('/game'); } });I understand that this does no work, and it will always render my actions view, perhaps you can't do it this way to begin with. My question is: am I going about this wrong? I'd rather not create different get functions for each view that I want.
最满意答案
您可以从req.params获取url参数,并构建关于该参数的逻辑。 对于你的情况,它可以是这样的:
app.get('/:view.ejs', function(req, res) { // Actions View if (req.xhr) { if (req.params.view === 'actions') { res.render('actions'); } else if (req.params.view === 'profile') { res.render('profile'); } } else { res.redirect('/game'); } });You can get url parameter from req.params, and build your logic regarding to that parameter. For your case, it can be something like this:
app.get('/:view.ejs', function(req, res) { // Actions View if (req.xhr) { if (req.params.view === 'actions') { res.render('actions'); } else if (req.params.view === 'profile') { res.render('profile'); } } else { res.redirect('/game'); } });更多推荐
发布评论