我的error handling程序如何优先于中间件

使用express.js作为一个项目,第一次使用它比搞乱更多,并且在获得中间件的过程中遇到一些麻烦。

我的问题是,调用我的快递静态路由,宣布接近文件的顶部

app.use(express.static(__dirname + '/public')); 

实际上是由error handling程序处理,几乎在文件的底部

 app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); 

…我不确定为什么。 我知道JS并不一定是按顺序执行的,但是我的理解是express会按顺序执行这些东西, app.use底部的东西会在app.use东西后面发生 – 因此需要next(); – 传递给下一个app.use处理程序?

任何想法/智慧? 任何帮助赞赏。

我有这个代码:

 // Initial variable setup var express = require('express'), favicon = require('serve-favicon'), logger = require('morgan'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'), swig = require('swig'), stylus = require('stylus'), nib = require('nib'), fs = require('fs'), app = express() ; app.use(express.static(__dirname + '/public')); app.engine('html', swig.renderFile); app.set('view engine', 'html'); (settings.deploymentMode === 'dev') && app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); function compile(str, path) { console.log('STYLUS: Compiling CSS'); return stylus(str) .set('filename', path) .set('compress', true) .use(nib()) .import('nib'); } app.use(stylus.middleware( { src: __dirname + '/public', compile: compile } )); // Got some routing going on here... app.get statements, all working fine. // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('system/error', { message: err.message, error: err }); }); } else { // Production error handler - @TODO: Rewrite this one first. app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('system/error', { message: err.message, error: {} }); }); } module.exports = app; 

Expresserror handling中间件使用四个参数来定义,而不是三个。

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

如果你只用3个参数来定义它,那么它就认为它是一个“正常的”中间件,并且会调用它,除非以前的中间件结束了请求而不是调用next() 。 看来,静态中间件调用next() ,可能允许后来的中间件logging或压缩其数据。