express 框架
路由
路由路径可以是字符串、字符串模式或正则表达式。
app.use(‘/example’, func) 表示匹配任意类型的请求
app.get(‘/example’, func) 表示匹配get请求
按照代码顺序,先匹配先执行。
可以使用一组回调函数处理一个路由
app.get('/example/c', [cb0, cb1, cb2], cb3, cb4);
express.Router
express.Router类是模块化的路由处理程序,分离程度更强,降低耦合,模块化。
代码如下:
var express = require('express');
var router = express.Router();
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
在程序中引入该模块:
var birds = require('./birds');
...
app.use('/birds', birds);
中间件
中间件函数能够访问请求对象 (req)、响应对象 (res) 以及应用程序的请求/响应循环中的下一个中间件函数。下一个中间件函数通常由名为 next 的变量来表示。
中间件函数可以执行以下任务:
1.执行任何代码。
2.堆请求和相应对象进行更改。
3.结束请求/响应循环。
4.调用堆栈中的下一个中间件。对于next的解释
next只是命名,取别的名字也是可以的,这是一个约定。
如果当前中间件函数没有结束请求/响应循环,那么它必须调用 next(),以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。调用next()会调用此路由中间件形参中的下一个方法,如果已经是最后一个形参了,则按照代码顺序继续往下搜寻满足条件的路由中间件。
以下示例显示中间件函数调用的元素:
应用层中间件
要跳过路由器中间件堆栈中剩余的中间件函数,请调用 next(‘route’) 将控制权传递给下一个路由。
next(‘route’) 仅在使用 app.METHOD() 或 router.METHOD() 函数装入的中间件函数中有效。使用app.use()无效,效果与next()相同。
app.get('/test', [cb1,cb2,cb3],function (req,res,next) {
next('route');
},function (req,res,next) {
console.log('after array')
next();
});
app.get('/test',function (req,res,next) {
res.send('test2');
})
//输出test2,控制台中无after array
app.get('/test', [cb1,cb2,cb3],function (req,res,next) {
next('route');
},function (req,res,next) {
console.log('after array')
next();
});
app.get('/test',function (req,res,next) {
res.send('test2');
})
//输出test2,控制台中有after array