koa中间件原理

作者: ysp123 | 来源:发表于2019-07-04 09:39 被阅读0次

之前有写过koa中间件的简单使用,简单回顾下:

//app.js
const   Koa = require('koa');
const   app = new Koa();
app.use(async (ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
    await next(); // 调用下一个middleware
});
app.use(async (ctx, next) => {
    const start = new Date().getTime(); // 当前时间
    await next(); // 调用下一个middleware
    const ms = new Date().getTime() - start; // 耗费时间
    console.log(`Time: ${ms}ms`); // 打印耗费时间
});
app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '<h1>Hello, koa2!</h1>';
});
app.listen(9091);

运行:

node app.js   //访问localhost:9091

以上就是koa中间件的使用,可以看出中间件的执行时通过use注册函数。知道use里执行中间件,构造一个服务,实现http访问。

//server.js
const http = require('http');
class Koa{
        createContent(req, res){
                const ctx = {
                      req, res
                }
                return ctx;
          }

        callback(){
              return (req, res)=>{
                  const ctx = this.createContent(req, res);
                  ctx.res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
                ctx.res.end("测试http服务");
            }
        }

        listen(port){
            const server = http.createServer(this.callback());
            server.listen(port);
        }
}
module.exports = Koa;

//app.js
const server = require('server.js');
const app = new server();
app.listen(9000);
node app.js  //执行app, http访问

服务核心use(中间件注册)

//server.js
const http = require('http');

function compose(middlewares){
           return function(){
                        function dispatch(i){
                              const fn = middllwares[i];
                              try{
                                    return Promise.resolve(
                                            fn(ctx, dispatch.bind(null, i+1));
                                        );
                                }catch(err){
                                    return  Promise.reject(err);
                              }
                        }
                        dispatch(0);
          }
}

class myKoa{
        constructor(){
              this.middleware = [];
        }        
        use(fn){
              this.middleware.push(fn);
              return this;
        }
        createContent(req, res){
                const ctx = {
                      req, res
                }
                return ctx;
          }

        callback(){
              return (req, res)=>{
                  const ctx = this.createContent(req, res);
                  //ctx.res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' });
                  //ctx.res.end("测试http服务");
                  
            }
        }

        listen(port){
            const server = http.createServer(this.callback());
            server.listen(port);
        }
}
module.exports = myKoa;

//app.js
const Iok = require('./myKoa.js');
const app = new Iok();
  app.use(async (ctx, next) => {
      console.log('lllll');
      await next();
      ctx.res.end('444444444444');
  });

  app.use(async (ctx) => {
      console.log('222222222222');
      ctx.res.end('66666666666666');
  });
  app.listen(9000);

以上就是实现koa的核心

相关文章

  • Koa中间件(middleware)级联原理

    前言 上次看到了koa-compose的代码,今天来说一下koa中间件的级联以及工作原理。 中间件工作原理 初始化...

  • 2018 各大公司最近面试题

    阿里 使用过的koa2中间件 koa-body原理 介绍自己写过的中间件 有没有涉及到Cluster 介绍pm2 ...

  • 面试题

    阿里 使用过的koa2中间件 koa-body原理 介绍自己写过的中间件 有没有涉及到Cluster 介绍pm2 ...

  • 2018大厂高级前端面试题汇总

    阿里 使用过的koa2中间件 koa-body原理 介绍自己写过的中间件 有没有涉及到Cluster 介绍pm2 ...

  • koa系列(三)

    文章内容:koa 中间件 以及 koa 中间件的执行流程。 一、什么是 Koa 的中间件 中间件就是匹配路由之前或...

  • 知识点总结

    Koa2中间件 koa(面向node.js的表达式HTTP中间件框架)、koa-router(路由中间件)、koa...

  • 手写一个 Koa --- Koa 原理学习

    一个学习 Koa 源码的例子 学习目标:原生 node 封装中间件路由静态文件服务(未完成待续) Koa 原理 一...

  • 8KOA 静态文件

    静态文件 使用 koa-static 中间件实现静态文件访问 安装中间件 使用中间件 使用 koa-mount 自...

  • koa中间件原理

    之前有写过koa中间件的简单使用,简单回顾下: 运行: 以上就是koa中间件的使用,可以看出中间件的执行时通过us...

  • koa

    koa 学习 中间件 koa-router koa-router 获取get/post请求参数 koa-bodyp...

网友评论

    本文标题:koa中间件原理

    本文链接:https://www.haomeiwen.com/subject/qscchctx.html