简易实现一个express

2,394

文章首发于:github.com/USTB-musion…

写在前面

Express是一个简洁、灵活的node.js Web应用开发框架,它提供一系列强大的特性,帮助你创建各种web和移动应用。丰富的HTTP快捷方法和任意排列组合的Connect中间件,让你创建健壮、友好的API变得既快捷又简单。

本文将从以下几部分进行总结:

  1. 路由的实现
  2. 中间件的实现
  3. 内置中间件实现

路由的实现

简单地说,就是根据方法和路径执行匹配成功后执行对应的回调函数。以下为路由的使用例子:

// express是一个函数
let express = require('./express-route')
// 监听函数
let app = express()

// RESTFUL API根据方法名的不同 做对应的资源的处理
app.get('/name', (req, res) => {
  res.end('name')
})

app.get('/age', (req, res) => {
  res.end('9')
})

app.post('/name', (req, res) => {
  res.end('post name')
})

// all匹配所有的方法, *表示匹配所有的路径
app.all('*', function(req, res) {
  res.end(req.method)
})

app.listen(3000, () => {
  console.log('server start 3000')
})

通过观察上面的例子可以发现,可以定义一个express-route.js文件,并暴露出express函数,get,post,all,listen等方法,将其引入即可运行上面的例子。以下为简易实现express路由的代码:

let http = require('http');
let url = require('url');
function createApplication() {
  // 监听函数
  let app = (req, res) => {
    // 取出每一个layer
    // 1. 获取请求的方法
    let getMethods = req.method.toLowerCase();
    let { pathname } = url.parse(req.url, true);

    for (let i = 0; i < app.routes.length; i++) {
      let {method, path, handler} = app.routes[i];
      if ((method === getMethods || method === 'all') && (path === pathname || path === '*')) {
        // 匹配成功后执行对应的callback
        handler(req, res);
      }
    }
    res.end(`Cannot ${getMethods} ${pathname}`)
  }
  // 存放路由
  app.routes = [];
  // 实现all方法
  app.all = function(path, handler) {
    let layer = {
      method: 'all', // 表示全部匹配
      path,
      handler
    }
    app.routes.push(layer);
  }
  // http.METHODS可以获取所有的http方法
  http.METHODS.forEach(method => {
    // 将方法名转换成小写的
    method = method.toLocaleLowerCase();
    // 实现get,post等方法
    app[method] = function(path, handler) {
      let layer = {
        method,
        path,
        handler
      }
      app.routes.push(layer);
    }
  })
  // 实现get方法
  // app.get = function(path, handler) {
  //   let layer = {
  //     method: 'get',
  //     path,
  //     handler
  //   }
  //   app.routes.push(layer);
  // }
  // 实现listen方法
  app.listen = function() {
    let server = http.createServer(app)
    server.listen(...arguments)
  }
  return app
}

module.exports = createApplication;

通过向外暴露一个createApplication函数,并返回app对象。通过http.METHODS可以获取所有的http方法,在app对象里定义listen,all还有get,post等请求方法。当客户端请求时即遍历routes,当匹配到理由时,即执行相应的handler函数。

中间件的实现

如上图所示,中间件就是处理HTTP请求的函数,用来完成各种特定的任务,比如检查用户是否登录,检查用户是否有权限访问,执行一个请求需要多长时间等。它的特点是:

  • 一个中间件处理完请求和响应后可以把相应的数据再传递给下一个中间件
  • 回调函数的next参数表示接受其他中间件的的调用
  • 可以根据路径区分返回执行不同的的中间件 以下为express中间件的简单使用例子:
// middleware use
// 中间件 在执行路由之前 要干一些处理工作 就可以采用中间件
let express = require('./express-middleware.js');

let app = express();

// use方法第一个参数缺省默认就是/
// 中间件可以扩展一些方法
app.use('/name', function(req, res, next) {
  res.setHeader('Content-Type','text/html;charset=utf-8');
  console.log('middleware1');
  next('名字不合法')
})

app.use('/', function(req, res, next) {
  console.log('middleware2');
  next();
})

app.get('/name', (req, res, next) => {
  // res.setHeader('Content-Type','text/html;charset=utf-8');
  res.end('姓名');
  next('名字不合法')
})

app.get('/age', (req, res) => {
  console.log(req.path);
  console.log(req.hostname);
  console.log(req.query);
  res.end('年龄');
})

// 错误中间件(4个参数)放在路由的下面
app.use(function(err, req, res, next) {
  console.log(err)
  next()
})

app.listen(3001, () => {
  console.log('server start 3001')
})

通过观察上面的例子可以发现,app.use方法调用中间件,其中next为非常重要的一个参数。要运行上面的例子,可以定义一个express-middware.js,来实现app.use方法,如果运行next,会调用下一个下一个中间件。其大致原理为:定义一个next函数并定义一个index索引值,每调用一次next,索引值加1。如果当前的layer与routes中的项相等,则匹配成功。实现express中间件的简易代码如下:

let http = require('http');
let url = require('url');
function createApplication() {
  // 监听函数
  let app = (req, res) => {
    // 取出每一个layer
    // 获取请求的方法
    let getMethods = req.method.toLowerCase();
    let { pathname } = url.parse(req.url, true);

    // 通过next方法进行迭代
    let index = 0;
    function next(err) {
      // 如果数组全部迭代完成还没有找到,说明路径不存在
      if (index === app.routes.length) {
        return res.end(`Cannot ${getMethods} ${pathname}`)
      }
      // 每次调用next方法调用下一个layer
      let { method, path, handler } = app.routes[index++];
      if (err) {
        // 如果有错误,应该去找错误中间件,错误中间件有一个特点,handler有4个参数
        if (handler.length === 4) {
          handler(err, req, res, next)
        } else {
          // 如果没有匹配到,要将err继续传递下去
          next(err); // 继续找下一个layer进行判断
        }
      } else {
        // 处理中间件
        if (method === 'middleware') {
          if (path === '/' || path === pathname || pathname.startsWith(path + '/')) {
            handler(req, res, next);
          } else {
            // 如果这个中间件没有匹配到,那么继续走下一个中间件匹配
            next(); 
          }
        } else { // 处理路由
          if ((method === getMethods || method === 'all') && (path === pathname || path === '*')) {
            // 匹配成功后执行对应的callback
            handler(req, res);
          } else {
            next();
          }
        }
      }
    }
    // 中间件中的next方法
    next();

    res.end(`Cannot ${getMethods} ${pathname}`)
  }
  // 存放路由
  app.routes = [];
  // 实现use方法
  app.use = function(path, handler) {
    // use方法第一个参数可以缺省,默认是/
    if (typeof handler !== 'function') {
      handler = path;
      path = '/';
    }
    let layer = {
      // 约定method是'middleware'就表示是一个中间件
      method: 'middleware', 
      path,
      handler
    }
    // 将中间件放在容器内
    app.routes.push(layer);
  }
  // express内置中间件
  app.use(function(req, res, next) {
    let { pathname, query } = url.parse(req.url, true);
    let hostname = req.headers['host'].split(':')[0];
    req.path = pathname;
    req.query = query;
    req.hostname = hostname;
    next();
  })
  // 实现all方法
  app.all = function(path, handler) {
    let layer = {
      method: 'all', // 表示全部匹配
      path,
      handler
    }
    app.routes.push(layer);
  }
  // http.METHODS可以获取所有的http方法
  http.METHODS.forEach(method => {
    // 将方法名转换成小写的
    method = method.toLocaleLowerCase();
    // 实现get,post等方法
    app[method] = function(path, handler) {
      let layer = {
        method,
        path,
        handler
      }
      app.routes.push(layer);
    }
  })
  // 实现listen方法
  app.listen = function() {
    let server = http.createServer(app)
    server.listen(...arguments)
  }
  return app
}

module.exports = createApplication;

内置中间件的实现

express通过中间件的形式扩展了很多的内置API,举一个简单的例子:

  app.use(function(req, res, next) {
    let { pathname, query } = url.parse(req.url, true);
    let hostname = req.headers['host'].split(':')[0];
    req.path = pathname;
    req.query = query;
    req.hostname = hostname;
    next();
  })

即可在req封装hostname, path, query, hostname。

你可以关注我的公众号「慕晨同学」,鹅厂码农,平常记录一些鸡毛蒜皮的点滴,技术,生活,感悟,一起成长。