简体   繁体   English

如何使用node / express将每个无效请求路由到默认路径

[英]How to route every invalid request to a default path using node/express

I'm trying to build a server that user will be able to enter these valid paths: 我正在尝试构建一个用户可以输入这些有效路径的服务器:

/art/thisProject
/art/thatProject

and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path /art/myProject : 如果用户输入其他任何无效的内容,例如这些用户将被重定向到root,然后重定向到默认路径/art/myProject

/some/url
/something
/another/u/rl

I guess the error comes because of a false use of "*" or with false understanding of how to override router rules. 我猜是由于错误使用"*"或对如何覆盖路由器规则的错误理解而导致的。

How do I do it? 我该怎么做?

this is my code: 这是我的代码:

app.get('/', function(req, res) {
    res.redirect('/art/myProject')
});

app.get('/art/:project', function(req, res){
    var project = req.param('project');
    var filePath = 'art/' + project + '/' + project;
    res.render(filePath)
});

app.get('*', function(req, res) {
    res.redirect('/')
});

This should work: 这应该工作:

app.get('/*', function(req, res) {
    res.redirect('/')
});

Or this: 或这个:

app.use(function(req, res) {
    res.redirect('/')
});

Both must of course be put last. 两者当然都必须放在最后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM