首页 > 编程语言 >Node学习——Koa框架

Node学习——Koa框架

时间:2024-02-02 10:05:31浏览次数:25  
标签:Node body const 框架 Koa 中间件 app ctx koa

1.简介

koa框架是一个遵循洋葱模型的轻量级的nodejs框架,将大部分工作都抛给中间件来处理,框架只专注于compose各个中间件,并按照use注册的顺序逐个执行中间件。

2.安装使用

安装:npm install koa -s使用:

const Koa = require('koa');
const app = new Koa;
app.listen(3000);

3.中间件的使用

const Koa  = require('koa');
const mount = require('koa-mount');

const app = new Koa();
app.use(mount('/api', function() {
      .....
}));
app.listen(80);

以上代码使用了koa-mount来进行进行路由处理,使用koa实例上的use方法将mount函数返回的函数注册为中间件。以下是koa中use函数。

use(fn) {
    if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
    if (isGeneratorFunction(fn)) {
      deprecate('Support for generators will be removed in v3. ' +
                'See the documentation for examples of how to convert old middleware ' +
                'https://github.com/koajs/koa/blob/master/docs/migration.md');
      fn = convert(fn);
    }
    debug('use %s', fn._name || fn.name || '-');
    this.middleware.push(fn);
    return this;
  }

可以看到,一个函数中间件在use函数中先是判断是否为generator函数,如果是,使用koa-convert转换,最终都会放入koa实例的middleware数组中保存,供后续调用。
a.说一下isGeneratorFunction函数,这个函数的思路是通过Function动态创建一个generate函数,然后取其原型与传入的函数的原型对比,如果相同说明传入函数就是generate函数。
b.再说一下convert函数,这个函数在koa-convert包中,就是内部又引入了co库,将传入的generate函数包裹,达到自执行的效果。

回过头说一下koa的listen函数,代码如下:

listen(...args) {
    debug('listen');
    const server = http.createServer(this.callback());
    return server.listen(...args);
  }

  callback() {
    const fn = compose(this.middleware);

    if (!this.listenerCount('error')) this.on('error', this.onerror);

    const handleRequest = (req, res) => {
      const ctx = this.createContext(req, res);
      return this.handleRequest(ctx, fn);
    };

    return handleRequest;
  }

可以看到,listen函数内部调用了node核心模块http,创建了一个http服务,并将自身的callback函数作为http服务的响应函数。
而callback函数内部则是通过compose将之前注册的中间件包裹,然后通过createContext将req和res封装到一个ctx中,逐层传入后面的中间件中。ctx内容如下:

Node学习——Koa框架_中间件

4.request和response处理

如上所示,req和res被封装到了context中,在各个中间件都可以从参数中得到,中间件可以拿到两个参数:一个是context,各中间件可以通过它来进行通信和同步状态;第二个是next,调用它会执行后续中间件。使用示例如下:

const Koa = require('koa')
const app = new Koa()
//声明一个main中间件,如果你急于了解中间件可以跳转到(三)
const main = (ctx,next) =>{
if (ctx.request.accepts('json')) {
    ctx.response.type = 'json';
    ctx.response.body = { data: 'Hello World' };
  } else if (ctx.request.accepts('html')) {
    ctx.response.type = 'html';
    ctx.response.body = '<p>Hello World</p>';
  } else if (ctx.request.accepts('xml')) {
    ctx.response.type = 'xml';
    ctx.response.body = '<data>Hello World</data>';
  } else{
    ctx.response.type = 'text';
    ctx.response.body = 'Hello World';
  };
}; //直接运行页面中会显示json格式,因为我们没有设置请求头,所以每一种格式都是ok的。   

app.use(main)//app.use()用来加载中间件。
app.listen(3000)

可以看到,我们给返回数据赋值可以直接使用’=‘赋值,在koa的response中body通过set属性,将设置进来的body值按照其type进行处理,如下。

  set body(val) {
    const original = this._body;
    this._body = val;

    // no content
    if (null == val) {
      if (!statuses.empty[this.status]) this.status = 204;
      if (val === null) this._explicitNullBody = true;
      this.remove('Content-Type');
      this.remove('Content-Length');
      this.remove('Transfer-Encoding');
      return;
    }

    // set the status
    if (!this._explicitStatus) this.status = 200;

    // set the content-type only if not yet set
    const setType = !this.has('Content-Type');

    // string
    if ('string' === typeof val) {
      if (setType) this.type = /^\s*</.test(val) ? 'html' : 'text';
      this.length = Buffer.byteLength(val);
      return;
    }

    // buffer
    if (Buffer.isBuffer(val)) {
      if (setType) this.type = 'bin';
      this.length = val.length;
      return;
    }

    // stream
    if (val instanceof Stream) {
      onFinish(this.res, destroy.bind(null, val));
      if (original != val) {
        val.once('error', err => this.ctx.onerror(err));
        // overwriting
        if (null != original) this.remove('Content-Length');
      }

      if (setType) this.type = 'bin';
      return;
    }

    // json
    this.remove('Content-Length');
    this.type = 'json';
  },

5.静态资源

使用koa-static中间件来处理静态资源,实例如下:
安装npm: npm install koa-static使用:

const Koa = require('koa');
const app = new Koa();
const path = require('path');
const serve = require('koa-static');

const main = serve(path.join(__dirname));

app.use(main);
app.listen(3000);

6.post请求的body处理

可以使用koa-body中间件来处理,
安装:npm install koa-body -s使用:

const Koa = require('koa');
const {koaBody} = require('koa-body');

const app = new Koa();
app.use(koaBody({
    multipart: true
});
app.use(function(ctx, next) {
    console.log(ctx.request.body);
});
app.listen(3000);

如上,koa-body会将post请求的body解析后保存在ctx中,供后续中间件使用。

标签:Node,body,const,框架,Koa,中间件,app,ctx,koa
From: https://blog.51cto.com/u_11365839/9541959

相关文章

  • 第17天:信息打点-语言框架&开发组件&FastJson&Shiro&Log4j&SpringBoot等
    框架:简单代码的一个整合库,如果使用框架就只需要学习使用框架调用即可如:文件上传功能是需要很多代码来实现的,框架把这个代码进行封封装,调用即可影响:如果采用框架开发,代码的安全性是取决于框架的过滤机制 #Python-开发框架-Django&FlaskDjango1、识别插件2、Set-Cookie:expi......
  • 响应式的 WebFlux 框架更优雅,性能更强!
    spring-webflux是spring在5.0版本后提供的一套响应式编程风格的web开发框架。这个框架包含了spring-framework和springmvc,它可以运行在Netty、Undertow以及3.1版本以上的Serlvet容器上。你可以在项目中同时使用spring-webmvc和spring-webflux,或者只用其中一个来开发web应用。所谓......
  • Blazor快速开发框架Known-更换数据库
    本文介绍如何更换框架默认的数据库,下面以MySQL数据库为例:操作步骤双击KIMS.Shared项目,打开项目文件,引用MySqlConnector数据库访问包<PackageReferenceInclude="MySqlConnector"Version="2.3.3"/>其他数据库访问包如下://SQLite<PackageReferenceInclude="Microsoft.Da......
  • 华为显卡已经支持pytorch计算框架
    相关链接:https://support.huawei.com/enterprise/zh/doc/EDOC1100079287/a21c08dehttps://www.zhihu.com/question/624955377/answer/3240350483https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/pies/pies_00004.htmlAscend/pytorch项目地址:https:......
  • 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextClock组件
    鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextClock组件一、操作环境操作系统: Windows10专业版、IDE:DevEcoStudio3.1、SDK:HarmonyOS3.1+编辑二、TextClock组件TextClock组件通过文本将当前系统时间显示在设备上。支持不同时区的时间显示,最高精度到秒级。子组件无。接口TextClock......
  • 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextPicker组件
    鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之TextPicker组件一、操作环境操作系统: Windows10专业版、IDE:DevEcoStudio3.1、SDK:HarmonyOS3.1+编辑二、TextPicker组件TextClock组件通过文本将当前系统时间显示在设备上。支持不同时区的时间显示,最高精度到秒级。子组件无。接口TextPic......
  • 【APP自动化进阶】APP自动化项目框架实战
    一、自动化项目介绍1.涉及技术栈pythonappiumseleniumpytestalluresubprocessadb2.实现的功能概述APP自动化执行支持pytest生成测试报告多线程执行自动开启、关闭appium、allure等服务二、框架及项目结构项目目录app---apk文件base---核心方法driver.py-......
  • Java 框架
    框架是整个或者部分系统的可重用设计,从应用角度看框架,可以被当作一组抽象构建及构件实例间交互的方法;从应用目的的角度看,SpringSpring定义Spring通常指的是SpringFramework,它是一个开源框架。Spring是包含众多工具方法的IoC容器。什么是容器容器时用来容纳某种物品的基......
  • nvm安装Nodejs时报错,Could not retrieve https://npm.taobao.org/mirrors/node/latest
    1.首先要使用管理员运行命令2.在安装nvm的目录下找到settings.txt,没有就手动增加一个node_mirror:https://npm.taobao.org/mirrors/node/npm_mirror:https://npm.taobao.org/mirrors/npm/这个地方有点奇怪,安装18的时候把上面的Https://去掉以后就下载成功了3.安装19以及......
  • 想要成为AIGC大模型工程师, 如何搭建你的知识体系框架?
    AI不会取代你的工作,会取代你的是会AI的人,如何提升自己与他人的知识壁垒,如何学习AIGC?相信在过去2023这个AI爆发的元年,我相信也是很多人的疑问,好像不懂使用点AI工具,例如ChatGpt、Midjourney或者SD,就好像被淘汰了一样,更近一步地我们如何训练自己的AI大模型、如何开发自己的AI产品?是很......