Express.js 4路由器如何让事情达到404页面

app.js生成器在app.js页面中生成以下代码:

 app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); 

但是,在文档中,它说

 Since path defaults to "/", middleware mounted without a path will be executed for every request to the app. 

并给出这个例子:

 // this middleware will not allow the request to go beyond it app.use(function(req, res, next) { res.send('Hello World'); }) // requests will never reach this route app.get('/', function (req, res) { res.send('Welcome'); }) 

那么,如果没有任何东西可以通过app.use('/', routes)行,那么404页面怎么能到达(或者/users app.use('/', routes)呢?

 app.use('/', routes); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); 

假设你的app.js有上面的代码(直接来自发生器),你的服务器接收到/foo的请求。 首先,你的app.use('/', routes); 中间件会检查它是否可以处理请求,因为它是在你的中间件堆栈中首先定义的。 如果routes对象包含/foo的处理程序,并且该处理程序调用res.send() ,则服务器完成处理请求,而其他中间件不执行任何操作。 但是,如果/foo的处理程序调用next()而不是res.send() ,或者如果routes对象根本不包含/foo的处理程序,那么我们继续下去中间件列表。

app.use('/users', users); 中间件不执行,因为请求不是/users/users/*

最后,404中间件最后执行,因为它是最后定义的。 由于它没有路由定义,它执行所有通过前两个中间件的请求。