简体   繁体   English

快速路由-根页和404

[英]Express Routing - Root Page and 404

I am working on a Node app that uses Express. 我正在使用Express的Node应用程序上工作。 In this app, I have the following: 在这个程序中,我有以下内容:

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

This route works fine for the positive case. 对于肯定的情况,此路线适用。 However, it fails for the negative case. 但是,在否定情况下失败。 For example, If I visit " http://www.example.com/404 ", I still see the index page. 例如,如果我访问“ http://www.example.com/404 ”,我仍然会看到索引页面。 In reality, I want it to fall through so that the Express Error handler tackles the error. 实际上,我希望它能够解决,以便Express Error处理程序能够解决错误。

How do I change my route so that when a person visits the root of my app, they see the home page. 如何更改路线,以便当一个人访问我的应用程序的根目录时,他们可以看到主页。 yet, if they enter anything else, they'll see the 404 page? 但是,如果他们输入其他任何内容,他们会看到404页面吗?

You want to use app.get() (or possibly app.all() ), not app.use() : 您要使用app.get() (或可能是 app.all() ),而不是app.use()

app.get('/', function(req, res) {
  res.render('index', {});
});

The reason why app.use('/', ...) matches /404 is explained here : app.use('/', ...)匹配/404原因在这里说明:

A route will match any path that follows its path immediately with a “/”. 路由将使紧跟其路径的任何路径都以“ /”匹配。 For example: app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on. 例如: app.use('/apple', ...)将匹配“ / apple”,“ / apple / images”,“ / apple / images / news”,依此类推。

You can define middleware to specifically handle errors. 您可以定义中间件以专门处理错误。

Express error-handling middleware takes four arguments and should be defined after all your other routes: Express错误处理中间件采用四个参数,应在所有其他路由之后定义:

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

app.use(function(err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

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

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