express框架layer.js源码解析

121 篇文章 1 订阅

layer.js是express框架的路由机制的底层数据结构。下面为主要源码,已经删除一些不太重要的代码。

function Layer(path, options, fn) {
  if (!(this instanceof Layer)) {
    return new Layer(path, options, fn);
  }

  debug('new %s', path);
  var opts = options || {};

  this.handle = fn;
  this.name = fn.name || '<anonymous>';
  this.params = undefined;
  this.path = undefined;
  this.regexp = pathRegexp(path, this.keys = [], opts);

  if (path === '/' && opts.end === false) {//use的时候end为false,route是true,也就是说use增加的函数,在所有的请求都和会被执行
    this.regexp.fast_slash = true;
  }
}

Layer.prototype.handle_error = function handle_error(error, req, res, next) {
  var fn = this.handle;

  if (fn.length !== 4) {
    // not a standard error handler
    return next(error);//跳过所有不是4个参数的函数,直接执行有四个参数的函数
  }

  try {
    fn(error, req, res, next);
  } catch (err) {
    next(err);
  }
};


Layer.prototype.handle_request = function handle(req, res, next) {
  var fn = this.handle;//handle可能是用户传进来的函数或者是route的dispatch

  if (fn.length > 3) {
    // not a standard request handler
    return next();//不标准的函数,直接跳过,把执行权交给栈里的下一个函数
  }

  try {
    fn(req, res, next);
  } catch (err) {//出错的话把执行权交给栈里的下一个函数,并且把错误的对象传过去
    next(err);
  }
};

核心的方法为上面的三个,其中还有一个match方法是用于判断路径是否匹配和提取url里的参数的。
1.首先我们看一下构造函数Layer,该函数返回一个对象,并在其中存储路由路径和对于的回调函数,该数据结构在express做路由选择时使用。
2。前缀为handle的两个函数根据前面的layer层的执行结果来判断执行哪个函数,并且根据node的约定,进行相关的参数个数检测,最后执行相关的fn回调,正常情况下是在fn函数的函数体代码中执行next来调到下一层,如果在fn回调执行的过程中出现错误,则执行catch中的代码next(err),从而执行下一个layer,并且把err参数传到下一层。
路由架构图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值