[英]Express js, how to match all routes, even sub routes
I am building a node js app that needs to return a 404 page for all routes except for the /video
route. 我正在构建一个节点js app,需要为除
/video
路由之外的所有路由返回404页面。
app.get('/video/*', Video.show)
app.get('*', (req,res) => res.render('not_found'))
This works if the URL does not have subdirectories. 如果URL没有子目录,则此方法有效。 The problem arises when someone enters a URL with subdirectories such as
/hello/subhello/
. 当有人输入带有子目录的URL时会出现问题,例如
/hello/subhello/
。 This is not caught by my routes. 我的路线没有抓到这个。
I already tried these options with no success: 我已经尝试过这些选项但没有成功:
app.get('/*', (req,res) => res.render('not_found'))
app.use((req,res) => res.render('not_found'))
Am I missing something ? 我错过了什么吗?
Thanks 谢谢
EDIT 编辑
When i remove the code to set up handlebars the routes are followed as expected. 当我删除代码以设置把手时,路线将按预期进行。
This is the handlebars set up code: 这是把手设置代码:
app.engine('.hbs', exphbs({
extname:'.hbs',
defaultLayout:'layout.hbs',
layoutsDir: __dirname+ '/views'
}))
app.set('view engine', '.hbs')
app.set('views', __dirname + '/views')
Here you have a working demo: 在这里你有一个工作演示:
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
app.engine('.hbs', exphbs({
extname:'.hbs',
defaultLayout:'layout.hbs',
layoutsDir: __dirname+ '/views'
}))
app.set('view engine', '.hbs')
app.set('views', __dirname + '/views')
app.get(['/videos', '/videos/*'], function (req, res) {
res.send('Hello World!');
});
app.use(function(req, res) {
res.status(404).send('Not found')
})
app.listen(1233, function () {
console.log('Example app listening on port 1233!');
});
Whether you access localhost:1233/videos or localhost:1233/videos/* you will get a Hello World response. 无论您是访问localhost:1233 / videos还是localhost:1233 / videos / *,您都会收到Hello World响应。 If you go somewhere else, you get the not found.
如果你去别的地方,就会找不到。
EDIT: Added handlebars code, same as you have. 编辑:添加了车把代码,与您一样。 Still works as expected.
仍然按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.