express提供丰富的http工具,快速处理请求,响应。核心功能中间件,路由,基于三个类来实现,Router,Layer,Route。javascript
主要核心内容:java
通常添加一个路由会这样写代码:express
app.get('/list', function (req, res) {
res.end('hello express');
});
复制代码
在Router里面作了一件事来支持这样的写法:数组
var methods = require('methods'); //包含http的方法名
methods.forEach((methods) => {
//拿到具体一个方法名 methods
Router.prototype[methods] = function() {
// 调用route方法往stack里面push一个路由
}
})
复制代码
express中路由和中间件都是放在了stack数组里面,那么就有顺序问题,若是use一个中间件那么须要放在路由前面。app
const express = require('express');
const app = new express();
app.use((req, res, next) => {
console.log('111');
next();
});
app.get('/list',(req, res) => {
res.end('hello express');
});
app.listen('8000');
复制代码
next表示经过,能够执行下个中间件或路由,若是发生错误,则能够抛出错误,交给错误中间件处理,错误中间件接受4个参数,4个参数的use就表明了错误中间件.第一个参数为错误信息函数
app.use((req, res, next) => {
console.log('111');
next(new Error('error'));
});
app.use((error, req, res, next) => {
console.log(error);
})
复制代码
当请求来时,会执行handle,循环stack,发现path相同,method相同,那么调用对应callback。这样处理,带来了一个问题,若是路由不断增多,stack数组会不断增大,匹配效率降低,为了提升效率,express引入了route,layer.工具
把同一个path造成一层,并提供match方法进行匹配判断,handle方法来执行当前层的深刻匹配methods。post
简单理解就是匹配一个路径,而后执行回调方法。ui
那么当一个路由注册的时候,则新生成一个Layer实例,若是剩下还有路由路径相同,则放在该层。怎么去放入这层的,在Route作。this
app.route('/list').get((req, res) => {
res.end('hello get');
}).post((req, res) => {
res.end('hello post');
}).put((req, res) => {
res.end('hello put');
}).delete((req, res) => {
res.end('hello delete');
});
复制代码
下面看一个伪代码,看如何去实现的app.route方法:
app.route = function(path) {
const route = new Route(path); // 生成一个route实例
const Layer = new Layer(path, route.dispatch.bind(route)); // 把route里面的dispatch方法做为Layer的处理函数
this.stack.push(layer); // 放入数组中
return route; // 返回route实例,用于链式调用,去注册method方法
}
复制代码