nodejs使得可以用javascirpt语言编写后台应用,但使用原生nodejs开发web应用非常复杂。Express是目前最流行的基于Node.js的Web开发框架,可以快速地搭建一个完整功能的网站。以下结合开发文档(opens new window)express源码(opens new window),整理出常用的一些API以及路由机制源码,使得读者理解更加通透。

#Express

  • static class
  • instance
    • 路由相关
      • app.use(path, callback) 主要用来添加非路由中间件,底层调用router.use()。
        • 匹配Path的方式:
          • 路径: /abcd
          • 路径模式: /abc?d
          • 正则表达式: //abc|/xyz/
          • 数组合集: [‘/abcd’, ‘/abc?e’, //abc|/xyz/]
      • app.all/METHOD(path, callback [, callback …]) 注册一个http请求路由
      • app.route(path) 获得route实例
    • 实例方法
      • app.get(name) 获取app上定义属性
      • app.set(name, value) 绑定或设置属性到app上
      • app.listen() 跟Node的http.Server.listen()一致

大部分情况app.use()和app.all()使用相似,最大不一样是中间件执行顺序。app.use()针对主进程,放前面跟放最后不一样;但app.all针对应用的路由,放的位置与中间件执行无关。stackoverflow

  1. var express = require('express')
  2. var logger = require('morgan')
  3. // 中间件
  4. app.use(logger()) // 每次都记录日志
  5. app.use(express.static(__dirname+'/public'))
  6. // 路由
  7. app.get('/api', (req, res) => res.send('api router'))
  8. app.listen(3000, () => console.log('success'))


Router

跟express路由API相似:

  • router.use(path, callback)
  • router.all/METHOD(path, [callback])
  • router.route() ```json var express = require(‘express’); var app = express();

// method方式路由 app.get(‘/api’, (req, res) => res.send(‘api router’)) app.get(‘/api/:id’, (req, res) => { res.send(‘api detail’) })

// method多回调路由 var cb0 = function (req, res, next) { console.log(‘CB0’); next(); } var cb1 = function (req, res, next) { console.log(‘CB1’); next(); } var cb2 = function (req, res) { res.send(‘Hello from C!’); } app.get(‘/example/c’, [cb0, cb1, cb2]);

// app.route方式路由 app.route(‘/example/d’) .get(function(req, res) { res.send(‘Get a random book’); }) .post(function(req, res) { res.send(‘Add a book’); }) .put(function(req, res) { res.send(‘Update the book’); });

// 子路由方式 var router = express.Router(); router.get(‘/user/:id’, function (req, res) { res.send(‘OK’); }); router.post(‘/user/:id’, function (req, res) { res.send(‘Post OK’); }); app.use(‘api’, router);

app.listen(3000);

  1. <a name="wV80L"></a>
  2. ## Request
  3. Express Request扩展了node http.IncomingMessage类,主要是增强了一些获取请求参数的便捷API。[源代码在这(opens new window)](https://github.com/expressjs/express/blob/master/lib/request.js)
  4. - req.headersextend http 返回header object对象
  5. - req.urlextend http 返回除域名外所有字符串
  6. - req.methodextend http 返回请求类型GET、POST等
  7. - req.get(name)/req.header(name) 底层调用node http 模块的req.headers
  8. - req.params 返回参数对象,对应的属性名由定义路由时确定。比如app.get('/user/:id')路由时,可以通过req。params.id取得参数
  9. - req.query 返回查询参数object对象。等同于qs.parse(url.parse(req.url,true).query)。
  10. - req.path 返回字符串。等同于url.parse(req.url).pathname。pathname跟req.url比,不带query后缀
  11. - req.body post请求获取到数据。需要使用[body-parser(opens new window)](https://www.npmjs.com/package/body-parser)中间件
  12. - req.cookies 拿到cookies值。需要使用[cookie-parser(opens new window)](https://www.npmjs.com/package/cookie-parser)中间件
  13. ```json
  14. // http://localhost:3000/api/1?type=123
  15. app.use((req, res, next) => {
  16. console.log(req.query) // { type: '123' }
  17. console.log(req.path) // /api/1
  18. console.log(req.params) // can got req.params.id
  19. console.log(req.body) // usually in post method
  20. console.log(req.cookies) // need cookie-parser middleware
  21. // extend http.IncomingMessage
  22. console.log(req.url) // /api/1?type=123
  23. console.log(req.headers) // header object
  24. console.log(req.method) // GET
  25. next()
  26. })

Response

Express Response扩展了node http.ServerResponse类,主要是增加一些便捷api以及返回数据时一些默认参数处理。源代码在这(opens new window)

  • 设置响应头
    • res.getHeader(name, value)extend http
    • res.setHeader(name, value)extend http
    • res.get(field) 底层调用res.getHeader()
    • res.set(field [, value])/res.header() 底层调用res.setHeader()
    • res.status(code) 底层直接赋值statusCode属性
    • res.type(type) 快捷设置Content-Type,底层调用res.set(‘Content-Type’, type)
    • res.cookie(name, value, options) 设置指定name的cookie。该功能express提供,而不是cookie-parser包实现。
    • res.clearCookie(name, options) 清楚指定name的cookie。
  • 发送数据
    • res.write(chunk[, encoding][, callback])extend http 写入数据
    • res.end([data] [, encoding])extend http。
    • res.send([body]) body可选:Buffer、object、string、Array。除非之前set过Content-Type,否则该方法会根据参数类型自动设置Content-Type,底层写入数据使用res.end()
    • res.json() 返回json对象。底层调用res.send()
    • res.redirect([status,] path) 302转发url
    • res.render(view [, locals] [, callback]) 输出对应html数据
    • res.sendStatus(statusCode) status和send的快捷键 ```json res.type(‘json’); // => ‘application/json’ res.header(‘Content-Type’, ‘text/plain’);

res.status(404).end(); res.status(404).send(‘Sorry, we cannot find that!’); res.status(500).json({ error: ‘message’ }); res.sendStatus(200); // equivalent to res.status(200).send(‘OK’)

  1. <a name="AsrQ6"></a>
  2. ## 路由机制源码解析
  3. 路由机制是express精髓。源码中,request、response、view模块都清晰易懂,可能就是router这块容易让人看糊涂。这里对express路由机制源码做下个人整理:
  4. <a name="RMBlh"></a>
  5. ### [#](https://lq782655835.github.io/blogs/node/node-code-express.html#express%E4%B8%8E%E5%AD%90%E8%B7%AF%E7%94%B1%E6%9C%89%E7%9B%B8%E5%90%8Capi)**express与子路由有相同API**
  6. 细心的读者可以发现,express实例和new Router()有一样的API:
  7. - express/router.use(path, callback)
  8. - express/router.all/METHOD(path, callback)。all只是METHOD的合集,故分为一类
  9. - express/router.route(path)
  10. 这是因为express实例中保存着一个单例模式的主Router对象(下文都叫主路由),这就意味着Router有的API都可以在express实例上。源码在application.js的[137行(opens new window)](https://github.com/expressjs/express/blob/master/lib/application.js#L137):
  11. ```json
  12. app.lazyrouter = function lazyrouter() {
  13. if (!this._router) {
  14. this._router = new Router({ // 单例模式的Router
  15. caseSensitive: this.enabled('case sensitive routing'),
  16. strict: this.enabled('strict routing')
  17. });
  18. // 默认应用两个中间件
  19. this._router.use(query(this.get('query parser fn')));
  20. this._router.use(middleware.init(this));
  21. }
  22. };


express/router.use(path, callback)

use方法一般用于执行中间件。这里为了方便理解,把一些参数处理等干扰代码省略了。我们可以很明显的看到,express.use使用了主路由use方法。所以简单理解express.use(args) = router.use(args)

  1. // application.js L187
  2. app.use = function use(fn) {
  3. // 获取单例主路由
  4. this.lazyrouter();
  5. var router = this._router;
  6. fns.forEach(function (fn) {
  7. if (!fn || !fn.handle || !fn.set) {
  8. // 交给router对象去处理
  9. return router.use(path, fn);
  10. }
  11. }, this);
  12. return this;
  13. };

现在去看下router中use方法,同样去除一些参数处理等干扰代码。最终定义了Layer对象把路径和回调函数做了包装,并把layer压入stack中,方便调用时循环stack以执行匹配的回调函数。

  1. // router/index.js L428
  2. proto.use = function use(fn) {
  3. // layer对象包装path和回调函数
  4. var layer = new Layer(path, {
  5. sensitive: this.caseSensitive,
  6. strict: false,
  7. end: false
  8. }, fn);
  9. // use通常是非路由中间件,故没有route实例
  10. layer.route = undefined;
  11. // 压入stack中,路由匹配时会从stack遍历
  12. this.stack.push(layer);
  13. return this;
  14. };

express/router.route(path)

该方法返回一个Route对象,注意是Route对象,不是Router对象。代码很简单,还是拿到主路由并调用主路由的route方法。

  1. // application L254
  2. app.route = function route(path) {
  3. this.lazyrouter();
  4. return this._router.route(path);
  5. };

router.route方法是每次新建一个Route对象(存储了定义的路由METHOD方法),同样经过Layer包装,压入stack,并最终返回该Route实例。所以简单理解,express.route(path) = new Route(path)
重点讲下为什么需要layer.route = route。路由匹配的两个必备匹配条件:path路径 + method方法。express.use这种执行中间件方法只要求有path就可以;express.get/post/…需要同时给到path和method,express.get/post/…底层都会调用express.route以得到一个Route实例。Route实例存储了对应路由上哪些方法被注册,比如只有get方式可以匹配到。所以当实际匹配路由时,从router的stack遍历找到对应layer后,如果是中间件就不找了,如果是路由方法则需要通过layer找到对应Route实例,再继续匹配。

  1. // router/index.js L491
  2. proto.route = function route(path) {
  3. // 创建了path下的Route
  4. var route = new Route(path);
  5. // 同样用layer包装。
  6. // 注意回调函数传递的是route.dispatch函数,这里是逻辑递增的关键
  7. // 保证了定义在路由上的多个中间件函数被按照定义的顺序依次执行
  8. var layer = new Layer(path, {
  9. sensitive: this.caseSensitive,
  10. strict: this.strict,
  11. end: true
  12. }, route.dispatch.bind(route));
  13. // route方法通常用于路由,需要知道具体的请求method
  14. // 所以需要从statck找到layer,再找到具体route
  15. // route实例上存储了对应path路由的哪些method
  16. layer.route = route;
  17. this.stack.push(layer);
  18. // 返回该route实例
  19. return route;
  20. };

express/router.all/METHOD(path, callback)

该方法用于注册一个get/post/…路由。从源码中可以看出,先实例化一个Route对象,最终执行的是该对象的METHOD方法。简单理解,express.get(args) = new Route().get(args)

  1. // application L472
  2. methods.forEach(function(method){
  3. this.lazyrouter();
  4. // 新实例化Route对象,并返回
  5. var route = this._router.route(path);
  6. // 执行Route对象的get/post/...方法
  7. route[method].apply(route, slice.call(arguments, 1));
  8. return this;
  9. });

接下来让我们看下Route对象下的METHOD方法。该方法也对回调函数进行了包装并且也存入stack中。由此可知,凡是路由机制API中有回调函数的,都会经过Layer进行包装。路由匹配到的时候会被调用。

  1. // router/route.js L92
  2. methods.forEach(function(method){
  3. Route.prototype[method] = function(){
  4. var handles = flatten(slice.call(arguments));
  5. for (var i = 0; i < handles.length; i++) {
  6. var handle = handles[i];
  7. // Route对象中,调用get/post方法也用Layer包装,并存储在stack
  8. var layer = Layer('/', {}, handle);
  9. layer.method = method;
  10. this.methods[method] = true;
  11. this.stack.push(layer); // 这里是Route对象的stack
  12. }
  13. return this;
  14. };
  15. });

路由匹配调用

在哪里判断是否匹配呢?从源码看你能得到app.handle—>Router.handle。以下是抽取的主要代码以及详细注视,以下的代码解释中能理解上面提到的所有内容。随手画了个执行流程图:
Express源码解析 - 图1

  1. proto.handle = function handle(req, res, out) {
  2. var self = this;
  3. // 拿到主路由的stack
  4. var stack = self.stack;
  5. // next方法循环处理stack
  6. next();
  7. function next(err) {
  8. var layer;
  9. var match;
  10. var route;
  11. // matchtrue以及idx小于stack长度才继续循环
  12. // 其他情况都跳出循环
  13. while (match !== true && idx < stack.length) {
  14. layer = stack[idx++];
  15. // 匹配path
  16. match = matchLayer(layer, path);
  17. route = layer.route;
  18. // 没有匹配到,继续下次循环
  19. if (match !== true) {
  20. continue;
  21. }
  22. // 无路由的中间件,跳出while循环(此时match = true)
  23. if (!route) {
  24. continue;
  25. }
  26. // 有路由的需要拿到route实例,再判断是否匹配到method
  27. var method = req.method;
  28. var has_method = route._handles_method(method);
  29. // 没有匹配到则继续循环,否则跳出循环
  30. if (!has_method && method !== 'HEAD') {
  31. match = false;
  32. continue;
  33. }
  34. }
  35. // 匹配到的layer都会执行到这
  36. // process_params主要处理express.param API,这里不展开
  37. self.process_params(layer, paramcalled, req, res, function (err) {
  38. if (err) {
  39. return next(layerError || err);
  40. }
  41. // layerhandle_request函数是执行回调函数
  42. // next函数传递下去是为了继续循环执行
  43. layer.handle_request(req, res, next);
  44. });
  45. }
  1. Layer.prototype.handle_request = function handle(req, res, next) {
  2. var fn = this.handle;
  3. if (fn.length > 3) {
  4. // not a standard request handler
  5. return next();
  6. }
  7. try {
  8. // 暴露给外面的回调函数,包含三个参数reqresnext
  9. // 所以这就解释了为什么一定要执行next()方法才能路由链路一直走下去
  10. fn(req, res, next);
  11. } catch (err) {
  12. next(err);
  13. }
  14. };


总结

  • Route模块对应的是route.js,主要是来处理路由信息的,每条路由都会生成一个Route实例。
  • Router模块下可以定义多个路由,也就是说,一个Router模块会包含多个Route模块。
  • express实例化了一个new Router(),实际上注册和执行路由都是通过调用Router实例的方法。类似于中介者模式
  • 凡事有回调的都是用Layer对象包装,Layer对象中有match函数来检验是否匹配到路由,handle_request函数来执行回调
  • 路由流程总结:当客户端发送一个http请求后,会先进入express实例对象对应的router.handle函数中,router.handle函数会通过next()遍历stack中的每一个layer进行match,如果match返回true,则获取layer.route,执行route.dispatch函数,route.dispatch同样是通过next()遍历stack中的每一个layer,然后执行layer.handle_request,也就是调用中间件函数。直到所有的中间件函数被执行完毕,整个路由处理结束。