每个中间件可以从App实例,接收三个参数,依次为request对象、response对象,和 web 应用中处于请求-响应循环流程中的中间件 ,一般被命名为 next 的变量 。每个中间件都可以对HTTP请求(request对象)进行加工,并且决定是否调用next方法,将request对象再传给下一个中间件。
app.get('/', function (req, res) {
res.send('root');
});
app.get('/example/a', function (req, res) {
res.send('Hello from A!');
});
// 正则
app.get('/ab?cd', function(req, res) {
res.send('ab?cd');
});
// 正则
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e');
});
// 正则
app.get('/user/*man', function(req, res) {
res.send('ab(cd)?e');
});
//使用多个回调函数处理路由
app.get('/example/b', function (req, res, next) {
console.log('response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from B!');
});
//使用回调函数数组处理路由
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
app.get('/example/c', [cb0, cb1]);
// 混合使用函数和函数数组处理路由
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
app.get('/example/d', [cb0, cb1], function (req, res, next) {
console.log('response will be sent by the next function ...');
next();
}, function (req, res) {
res.send('Hello from D!');
});