路由处理器和中间件的参数中都有回调函数,这个函数有2个3个或4个参数。
如果有2个或3个参数,前两个参数是请求和响应对象,第三个参数是next函数。
如果有4个参数,它就变成了错误处理中间件,第一个参数变成了错误对象,然后依次是请求、响应和next对象。
如果不调用next(),管道就会被终止,也不会再有处理器或中间件做后续处理,此时应该发送一个响应到客户端。
var app = require(‘express‘)();
let i=1;
app.use(function(req, res, next){
console.log(‘\nALLWAYS‘+i++);
next();
});
app.use(function(req, res, next){
console.log(‘SOMETIMES‘);
next();
});
//错误处理中间件
app.use(function(err, req, res, next){
console.log(‘unhandled error detected: ‘ + err.message);
res.send(‘500 - server error‘);
});
app.use(function(req, res){
console.log(‘route not handled‘);
res.send(‘404 - not found‘);
});
app.listen(3000, function(){
console.log(‘listening on 3000‘);
});
var app = require(‘express‘)();
let i=1;
app.use(function(req, res, next){
console.log(‘\nALLWAYS‘+i++);
next();
});
app.get(‘/a‘, function(req, res){
console.log(‘/a: route terminated‘);
res.send(‘a‘);
});
app.get(‘/a‘, function(req, res){
console.log(‘/a: never called‘);
});
app.use(function(req, res, next){
console.log(‘SOMETIMES‘);
next();
});
//错误处理中间件
app.use(function(err, req, res, next){
console.log(‘unhandled error detected: ‘ + err.message);
res.send(‘500 - server error‘);
});
app.use(function(req, res){
console.log(‘route not handled‘);
res.send(‘404 - not found‘);
});
app.listen(3000, function(){
console.log(‘listening on 3000‘);
});
var app = require(‘express‘)();
let i=1;
app.use(function(req, res, next){
console.log(‘\nALLWAYS‘+i++);
next();
});
app.get(‘/b‘, function(req, res, next){
console.log(‘/b: route not terminated‘);
next();
});
app.use(function(req, res, next){
console.log(‘SOMETIMES‘);
next();
});
app.get(‘/b‘, function(req, res, next){
console.log(‘/b (part 2): error thrown‘ );
throw new Error(‘b failed‘);
});
app.use(‘/b‘, function(err, req, res, next){
console.log(‘/b error detected and passed on‘);
next(err);
});
//错误处理中间件
app.use(function(err, req, res, next){
console.log(‘unhandled error detected: ‘ + err.message);
res.send(‘500 - server error‘);
});
app.use(function(req, res){
console.log(‘route not handled‘);
res.send(‘404 - not found‘);
});
app.listen(3000, function(){
console.log(‘listening on 3000‘);
});
var app = require(‘express‘)();
let i=1;
app.use(function(req, res, next){
console.log(‘\nALLWAYS‘+i++);
next();
});
app.use(function(req, res, next){
console.log(‘SOMETIMES‘);
next();
});
app.get(‘/c‘, function(err, req){
console.log(‘/c: error thrown‘);
throw new Error(‘c failed‘);
});
app.use(‘/c‘, function(err, req, res, next){
console.log(‘/c: error deteccted but not passed on‘);
next();
});
//错误处理中间件
app.use(function(err, req, res, next){
console.log(‘unhandled error detected: ‘ + err.message);
res.send(‘500 - server error‘);
});
app.use(function(req, res){
console.log(‘route not handled‘);
res.send(‘404 - not found‘);
});
app.listen(3000, function(){
console.log(‘listening on 3000‘);
});