koa2 mysql 中间件_Koa2第二篇:中间件

第一篇介绍了生成器目录设计。xyzcoding:Koa2第一篇:详解生成器​zhuanlan.zhihu.com0d0d5ed28c8faff90463c18f6eb9a31d.png

接下来学习Koa2的中间件。

Koa2本身只能算一个极简的HTTP服务器,自身不内置中间件,但是提供中间件内核。中间件是Koa2的核心,因此需要熟练掌握。

中间件是什么?

你可以把一个HTTP请求理解为水流,而各种各样的中间件类似各种管道,它会对水流进行处理。每个中间件在HTTP请求过程中会改写请求,响应等数据。

也就是我们常说的洋葱模型。

我们可以通过一个实例理解上述的过程:

const Koa = require('koa')

const app = new Koa()

// 日志中间件app.use(async (ctx, next) => {

console.log('middleware before await');

const start = new Date()

await next() // 函数控制权转移 console.log('middleware after await');

const ms = new Date() - start

console.log(`${ctx.method}${ctx.url}-${ms}ms`)

})

app.use(async(ctx, next) => {

console.log('response');

ctx.body = "hello koa2"

})

module.exports = app

终端:

middleware before await

response

middleware after await

中间件写法

通用函数中间件

// 日志中间件app.use((ctx, next) => {

console.log('middleware before await');

const start = new Date()

return next().then(() => {

console.log('middleware after await');

const ms = new Date() - start

console.log(`${ctx.method}${ctx.url}-${ms}ms`)

})

})

上述写法不够简洁。

生成器函数中间件

const convert = require('koa-convert');

// 日志中间件app.use(function* log(next) {

console.log('middleware before await');

const start = new Date()

yield next

const ms = new Date() - start

console.log(`${this.method}${this.url}-${ms}ms`)

})

这里有个小细节,因为我们这里中间件没有使用箭头函数,因此其实这里的this就是我们平时说的上下文对象ctx。这也说明了使用async箭头函数式中间件时候,为什么Koa2需要显示提供ctx对象, 就是为了解决此处用this引用会有问题。

async函数中间件

app.use(async ctx => {

ctx.body = 'Hello World';

});

上下文对象

在Koa2中,ctx是一次完整的HTTP请求的上下文,会贯穿这个请求的生命周期。也就是说在整个请求阶段都是共享的。

createContext(req, res) {

const context = Object.create(this.context);

// request、response是Koa2内置的对象 // 业务中我们一般通过ctx.request、ctx.response访问 const request = context.request = Object.create(this.request);

const response = context.response = Object.create(this.response);

// 挂在app自身 context.app = request.app = response.app = this;

// 挂在node原生的内置对象 // req: http://nodejs.cn/api/http.html#http_class_http_incomingmessage // res: http://nodejs.cn/api/http.html#http_class_http_serverresponse context.req = request.req = response.req = req;

context.res = request.res = response.res = res;

request.ctx = response.ctx = context;

request.response = response;

response.request = request;

// 最初的URL context.originalUrl = request.originalUrl = req.url;

// 一个中间件生命周期内公共的存储空间 context.state = {};

return context;

}

ctx.body

ctx.body主要是Koa2返回数据到客户端的方法。

// context.js

/**

* Response delegation.

*/

delegate(proto, 'response')

.access('body')

可见ctx.body实际上是对在response.js的body进行赋值操作。

ctx.body的一些特性:可以直接返回一个文本

可以返回一个HTML文本

可以返回JSON

ctx.body = 'hello'

ctx.body = '

h2

'

ctx.body = {

name: 'kobe'

}

get status() {

return this.res.statusCode;

},

/*** Set response status code.** @param {Number} code* @api public*/

set status(code) {

if (this.headerSent) return;

assert(Number.isInteger(code), 'status code must be a number');

assert(code >= 100 && code <= 999, `invalid status code:${code}`);

this._explicitStatus = true;

this.res.statusCode = code;

// 客户端发送的 HTTP 版本,message.httpVersionMajor 是第一个整数, message.httpVersionMinor 是第二个整数。 // http://nodejs.cn/api/http.html#http_message_httpversion // 设置状态消息 http://nodejs.cn/api/http.html#http_response_statusmessage if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code];

if (this.body && statuses.empty[code]) this.body = null;

},

/*** Set response body.** @param {String|Buffer|Object|Stream} val* @api public*/

set body(val) {

// this._body是真正的body属性或者说代理属性 const original = this._body;

this._body = val;

// no content if (null == val) {

// 204 "no content" 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;

}

// 设置状态码 if (!this._explicitStatus) this.status = 200;

// 设置content-type const setType = !this.has('Content-Type');

// string if ('string' === typeof val) {

// text/html or text/plain if (setType) this.type = /^\s*

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';

},

ctx.body的工作原理就是根据其赋值的类型,来对Content-Type头进行处理,最后根据Content-Type类型值通过res.end,把数据写入到浏览器。

ctx.redirect

浏览器重定向一般是向前或者向后重定向。

redirect(url, alt) {

// location if ('back' === url) url = this.ctx.get('Referrer') || alt || '/';

this.set('Location', encodeUrl(url));

// status if (!statuses.redirect[this.status]) this.status = 302;

// html if (this.ctx.accepts('html')) {

url = escape(url);

this.type = 'text/html; charset=utf-8';

this.body = `Redirecting to ${url}.`;

return;

}

// text this.type = 'text/plain; charset=utf-8';

this.body = `Redirecting to${url}.`;

},

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/383016.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql命令行如何建库_MySQL心得2--命令行方式建库和表

1.创建使用create database或create schema命令可以创建数据库。create database 库名create database if not exists 库名(创建库并检验创建的库是否存在&#xff0c;不存在则建&#xff0c;存在就不建了)MySQL不允许两个数据库使用相同的名字&#xff0c;使用ifnot exists从句…

python 少儿趣味编程下载_PYTHON少儿趣味编程

章认识Python11.1编程语言和Python11.1.1程序设计和编程语言11.1.2Python简介21.2Python的安装41.2.1Windows下的Python安装41.2.2MAC下的Python安装81.3个程序HelloWorld111.4开发工具IDLE121.4.1IDLE简介121.4.2用IDLE编写程序121.4.3IDLE的其他功能161.5小结18第2章变量、数…

rs485数据线接反_终于有人把RS485通讯的正确接线方式讲明白了,网友:这下好办了...

RS485是一个定义平衡数字多点系统中的驱动器和接收器的电气特性的标准,该标准由电信行业协会和电子工业联盟定义。使用该标准的数字通信网络能在远距离条件下以及电子噪声大的环境下有效传输信号。RS485使得廉价本地网络以及多支路通信链路的配置成为可能。那么RS485通讯的正确…

骑马与砍杀python代码_GitHub - yunwei1237/scottish-fold: 一个关于骑马与砍杀的剧本制作工具...

scottish-fold一个关于骑马与砍杀的剧本简单快速的制作工具前言​在很久以前的时候&#xff0c;也就是刚开始玩骑砍的时候就想着能够制作一个自己的剧本&#xff0c;用于书写自己想要的故事。当我怀着远大的梦想去这么做的时候才发现&#xff0c;原来制作剧本没有自己想象的那么…

java tomcat 监控_java程序监控tomcat实现项目宕机自动重启并发送邮件提醒

最近由于老项目频繁挂掉&#xff0c;由于项目经过多批人之手&#xff0c;短时间难以定位问题&#xff0c;所以只好写一个监控程序。 时间比较紧半天时间&#xff0c;而且水平有限大神勿喷&#xff0c;有好的方法还请赐教。 1、问题描述&#xff1a;分两种情况1.1、tomcat 彻底挂…

java静态类和非静态类的区别_Java中静态内部类和非静态内部类到底有什么区别?...

内部类(Inner Class)和静态内部类(Static Nested Class)的区别&#xff1a;定义在一个类内部的类叫内部类&#xff0c;包含内部类的类称为外部类。内部类可以声明public、protected、private等访问限制&#xff0c;可以声明 为abstract的供其他内部类或外部类继承与扩展&#x…

java写便签_如何编写一个便签程序(用Java语言编写)

如何编写一个便签程序(用Java语言编写)热度&#xff1a;336 发布时间&#xff1a;2011-02-18 11:44:16如何编写一个便签程序(用Java语言编写)因为以前没有好好学习Java&#xff0c;都搞忘了&#xff0c;请大家原谅&#xff0c;也请你们指导一下&#xff0c;怎么编写这个程序&…

java 生成log4j_Java log4j配置每天生成一个日志文件 - 永恒ぃ☆心 的日志 - 网易博客...

一、配置属性文件log4j.propertieslog4j.rootLoggerINFO,stdout,Rlog4j.appender.stdoutorg.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layoutorg.apache.log4j.PatternLayout# Pattern to output the callers file name and line number.log4j.appender.stdout.layo…

java 子进程输出流_具有输入/输出流的Java进程

首先&#xff0c;我建议更换这条线路。Process process Runtime.getRuntime ().exec ("/bin/bash");带着线条ProcessBuilder builder new ProcessBuilder("/bin/bash");builder.redirectErrorStream(true);Process process builder.start();ProcessBuil…

java中if 运算符_[Java]Java基本语法结构(运算符,流程控制语句,if语句)

1:运算符(掌握)(1)算术运算符A:,-,*,/,%,,--B:的用法a:加法b:正号c:字符串连接符C:/和%的区别数据做除法操作的时候&#xff0c;/取得是商&#xff0c;%取得是余数D:和--的用法a:他们的作用是自增或者自减b:使用**单独使用放在操作数据的前面和后面效果一样。a或者a效果一样。*…

java 变量取值范围_JAVA中的变量及取值范围

字节是二进制数据的单位。一个字节通常8位长。但是&#xff0c;一些老型号计算机结构使用不同的长度。为了避免混乱&#xff0c;在大多数国际文献中&#xff0c;使用词代替byte。变量&#xff1a;变量的数据类型&#xff1b;变量名变量值数据类型基本型数值型(整数)布尔型浮点型…

java object强制类型转换_scala object 转Class Scala强制类型转换

asInstanceOf[T]将对象类型强制转换为T类型。还是由于泛型存在类型擦除的原因,1.asInstanceOf[String]在运行时会抛出ClassCastException异常&#xff0c;而List(1).asInstanceOf[List[String]]将不会。packageresti.webimportorg.springframework.beans.factory.annotation.Au…

java毛玻璃_模糊效果(毛玻璃效果)

模糊效果(毛玻璃效果)效果演示&#xff1a;1. 使用iOS自带的 UIImageImageEffects 文件文件中有这么几个方法&#xff1a;- (UIImage *)applyLightEffect;- (UIImage *)applyExtraLightEffect;- (UIImage *)applyDarkEffect;- (UIImage *)applyTintEffectWithColor:(UIColor *)…

java程序崩溃怎么重启_android 异常崩溃后 重启app(进程守护方式实现)

【实例简介】【实例截图】【核心代码】package com.sunfusheng.daemon.sample;import android.content.ComponentName;import android.content.Intent;import android.os.Looper;import android.util.Log;import com.blankj.utilcode.util.AppUtils;import com.sunfusheng.daem…

mysql 存储过程 循环结构 命名_mysql存储过程----循环结构

循环结构一共分为三种&#xff1a;三种循环结构分别为while、repeat、loop。while循环语法while 表达式(如果表达式为true则执行业务逻辑&#xff0c;否则不执行&#xff0c;与repeat循环相反&#xff0c;repeat循环满足表达式退出循环&#xff0c;不满足一直执行) do业务逻辑e…

mysql 组合索引 or_Mysql_组合索引和单列索引

一、目标什么时候使用组合索引&#xff0c;什么时候使用单独索引组合索引、单独索引区别组合索引&#xff1a;最左前缀匹配原则二、前期数据准备1. 建表CREATE TABLE user (uidint(11) NOT NULLAUTO_INCREMENT,namevarchar(50) DEFAULT NULL,pwdvarchar(50) DEFAULT NULL,creat…

mysql与mangodb多租户_MongoDB多租户(Java):如何使用MongoClient在运行时切换具有不同数据库凭据的MongoDB数据库?...

我正面临一个关于MongoDB多租户的问题.我有两个不同的mongoDB数据库(db1和db2).这两者都有不同的凭据.db1凭据&#xff1a;userName&#xff1a;admin密码&#xff1a;passwddb2凭据&#xff1a;userName&#xff1a;admin1密码&#xff1a;passwd1我需要在运行时从一个数据库切…

python 库 全局变量_python局部变量和全局变量global

当你在函数定义内声明变量的时候&#xff0c;它们与函数外具有相同名称的其他变量没有任何关系&#xff0c;即变量名称对于函数来说是 局部 的。这称为变量的 作用域 。所有变量的作用域是它们被定义的块&#xff0c;从它们的名称被定义的那点开始。使用局部变量例7.3 使用局部…

java 自省_自知 自省 自立 自信 自尊 自治 自强 自制

自知 自省 自立 自信 自尊 自治 自强 自制能知人者有智力&#xff0c;能自知才是真正的智者&#xff1b;能战胜别人者有力量&#xff0c;能战胜自己才是真正的强者&#xff1b;能知足者就是富有&#xff0c;能勤奋顽强坚持才是真正的有志者&#xff1b;不失其立足之地的人可以长…

java中json重复数据结构_JAVA把各种数据结构转换为JSON格式

Java代码import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import net.sf…