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

Sta*_*tec 9 javascript node.js express

express生成器在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);
});
Run Code Online (Sandbox Code Playgroud)

但是,在文档中,它说

Since path defaults to "/", middleware mounted without a path will be executed for every request to the app.
Run Code Online (Sandbox Code Playgroud)

并给出了这个例子:

// 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');
})
Run Code Online (Sandbox Code Playgroud)

那么,如果没有任何东西可以通过这条线,怎么能够到达404页面(或者/users那个问题的路线)app.use('/', routes)呢?

小智 14

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);
});
Run Code Online (Sandbox Code Playgroud)

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

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

最后,404中间件最后执行,因为它是最后定义的.由于它是在没有路由的情况下定义的,因此它会针对通过前两个中间件的所有请求执行.