koa文档

简介

koa 是由 Express 原班人马打造的,致力于成为一个更小、更富有表现力、更健壮的 Web 框架。使用 koa 编写 web 应用,通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升错误处理的效率。koa 不在内核方法中绑定任何中间件,它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手。

koa1.x的用generator, koa2.x用async/await, node各个版本对es6的支持程度,可参考 node.green

Koa 应用是一个包含一系列中间件 generator 函数的对象。 这些中间件函数基于 request 请求以一个类似于栈的结构组成并依次执行。 Koa 类似于其他中间件系统(比如 Ruby's Rack 、Connect 等), 然而 Koa 的核心设计思路是为中间件层提供高级语法糖封装,以增强其互用性和健壮性,并使得编写中间件变得相当有趣。

Koa 包含了像 content-negotiation(内容协商)、cache freshness(缓存刷新)、proxy support(代理支持)和 redirection(重定向)等常用任务方法。 与提供庞大的函数支持不同,Koa只包含很小的一部分,因为Koa并不绑定任何中间件。

hello world示例:

//koa 2.x

var Koa = require('koa');

var app = new Koa();

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

ctx.body = 'Hello World';

});

app.listen(3000);

console.log('server listening at 3000');

中间件

Koa 的中间件通过一种更加传统(您也许会很熟悉)的方式进行级联,摒弃了以往 node 频繁的回调函数造成的复杂代码逻辑。 我们通过 generators 来实现“真正”的中间件。 Connect 简单地将控制权交给一系列函数来处理,直到函数返回。 与之不同,当执行到 yield next 语句时,Koa 暂停了该中间件,继续执行下一个符合请求的中间件('downstrem'),然后控制权再逐级返回给上层中间件('upstream')。

koa1.x 和 koa2.x的中间件机制是一样的,区别在于koa1.x用generator书写,koa2.x用async/await; async/await本质上是generator的语法糖,generator的本质是一个迭代器,需要runner去触发下一阶段的执行.

中间件的栈执行顺序(后进先出),类似html标签层层嵌套,从顶层到底层,在从底层开始闭合(其实dom的事件机制也类似)

示例:

//> koa 2.x

var Koa = require('koa');

var app = new Koa();

// mw: x-response-time

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

let start = new Date;

await next();

let ms = new Date - start;

ctx.set('X-Response-time', ms + 'ms');

});

// mw: logger

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

let start = new Date;

await next();

let ms = new Date - start;

console.log('%s %s - %d', ctx.method, ctx.url, ms);

});

// mw: response

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

ctx.body = 'Hello World'; // 设置响应内容后,还可以 ctx.se(..) 设置响应头

});

app.listen(3012);

console.log('server listening at 3012');

//> koa 1.x

var koa = require('koa');

var app = koa();

// x-response-time

app.use(function* (next) {

let start = new Date;

yield next;

var ms = new Date - start;

this.set('X-Response-Time', ms + 'ms');

});

// logger

app.use(function* (next) {

let start = new Date;

yield next;

let ms = new Date - start;

console.log('%s %s - %d', this.method, this.url, ms);

});

// response

app.use(function* (next) {

this.body = 'Hello World~~';

});

app.listen(3012);

console.log('server listen at 3012');

配置

app实例的配置属性:

app.name 应用名称

app.env 环境变量(默认为 process.env.NODE_ENV || 'development')

app.proxy 若为true, 则解析header(请求头),并支持 X-Forwarded-Host

app.subdomainOffset 默认2,表示 app.subdomains, 所忽略的segment个数

app.listen(port)

app.listen(3000) 创建并返回一个http服务器.

// app.listen() 同下

var http = require('http');

http.createServer(app.callback()).listen(3000);

http.createServer(app.callback()).listen(3001); // 同一个应用运行在多个端口上

app.callback()

app.callback() 返回request callback函数,可用于 http.createServer(app.callback())

app.use(middleware)

app.use(mw) 为应用添加中间件

app.keys

app.keys = ['i am secrect', 'hello'] 设置 signed cookie 的密钥

ctx.cookies.set('name', 'sandy', {signed: true}) 设置加密的cookie

错误处理

默认所有的错误信息会输出到 stderr, 可以监听error事件,实现自动的错误处理.

app.on('error', function(err, context) {

// 若处理请求阶段出错,不能响应时,会有context参数传入回调

console.error('server error:', err);

});

上下文对象

Koa Context 将 node 的 request 和 response 对象封装在一个单独的对象里面,其为编写 web 应用和 API 提供了很多有用的方法。

context 在每个 request 请求中被创建.

koa 1.x 的上下文对象为中间件的 this, koa 2.x 的上下文对象,为中间件的参数1

// koa 1.x

app.use(function* (next) {

this.body = 'good'; // this is context obj

});

// koa 2.x

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

ctx.body = 'good2'; // ctx is context obj

});

为了便于访问和调用,许多 context 的属性和方法,代理了 ctx.request 和 ctx.response 所对应的等价方法, 比如说 ctx.type 和 ctx.length 代理了 response 对象中对应的方法,ctx.path 和 ctx.method 代理了 request 对象中对应的方法。

ctx.req nodejs的request对象

ctx.res nodejs的response对象

ctx.request koa的request对象, 包装后的nodejs的request对象

ctx.response koa的response对象

ctx.app 应用实例的引用

ctx.cookies.get(name, [options]) 获取coolie, koa使用了Express的cookies模块

ctx.cookies.set(name, value, [options]) 设置cookie,

options = {

signed: true,

expires: time,

path: '/',

domain: 'a.com',

secure: false,

httpOnly: true

}

ctx.throw(msg, [status]) 抛出异常

// 适配 msg status两个参数的顺序,缺少的则用默认值

ctx.throw(403);

ctx.throw('some error');

ctx.throw('name required', 400);

ctx.throw(400, 'name required');

ctx.response ctx.response = false 时,可以通过ctx.res直接使用原生的response对象, 但不推荐这样做

ctx.request对象释放到 ctx上的方法和属性

// url and method

ctx.url

ctx.originalUrl read only

ctx.protocol read only

ctx.host read only

ctx.hostname read only

ctx.path

ctx.query

ctx.querystring

ctx.method

// header

ctx.header read only

ctx.get(headerName)

ctx.is() 判断 content-type

ctx.accepts() accepts content-type

ctx.acceptsEncodings()

ctx.acceptsLanguage()

ctx.accepetsCharsets()

// others

ctx.ip read only

ctx.ips read only

ctx.secure read only

ctx.subdomains read only

ctx.fresh read only

ctx.stale read only

ctx.socket read only

ctx.response对象释放到 ctx 上的方法和属性

// 响应体

ctx.body

ctx.attachment()

// 响应头

ctx.set(name,val) 设置响应头

ctx.remove() 删除响应头

ctx.status 状态码

ctx.length content-length

ctx.type content-type

ctx.lastModified 缓存相关响应头

ctx.etag

// 其他

ctx.headerSent 是否已发送响应头

ctx.redirect() 重定向

ctx.request对象的完整属性方法

// url and method

ctx.request.method

ctx.request.url

ctx.request.originalUrl

ctx.request.protocol

ctx.request.host hostname:port

ctx.request.hostname

ctx.request.path

ctx.request.query eg: {color: 'blue', size: 'small'} 不支持嵌套对象

ctx.request.querystring eg: foo=bar&go=fine

ctx.request.search eg: ?foo=bar&go=fine

// header

ctx.request.get()

ctx.request.header

ctx.request.type content-type eg: image/png

ctx.request.length cotent-length

ctx.request.charset eg: utf-8

ctx.request.is() eg: ctx.is('html'), ctx.is('text/html'), ctx.is('html', 'application/*'), ctx.is('application/json')

// others

ctx.request.fresh 若用(*If-None-Match/ETag, If-Modified-Since/Last-Modified)进行缓存协商,则该属性表示协商结果

ctx.request.stale 与 ctx.request.fresh 相反

ctx.request.secure

ctx.request.ip

ctx.request.ips

ctx.request.subdomains

ctx.request.socket

ctx.request.idempotent 请求是否幂等

// 内容协商

ctx.request.accepts(types) eg: ctx.accepts('html') ctx.accepets('json', 'text')

ctx.request.acceptsEncoding(encodings) eg: ctx.acceptsEncodings('gzip', 'deflate','identity')

ctx.request.acceptsLanguages(langs) eg: this.acceptsLanguages('es', 'en')

ctx.request.acceptsCharsets(charsets) eg: ctx.acceptsCharsets('utf-8')

ctx.response对象的完整属性

// 响应体

ctx.response.body eg: ctx.body = String/Buffer/Stream/Object

ctx.response.attachment([filename])

// 响应头

ctx.response.get(field) eg: ctx.response.get('ETag') 响应头(field)不区分大小写

ctx.response.set(field, value) eg: ctx.set('cache-control', 'no-cache')

ctx.response.remove(field)

ctx.response.append(field, val) 为指定头部追加值

ctx.response.header

ctx.response.status eg: ctx.response.status = 301;

ctx.response.statusString

ctx.response.length content-length

ctx.response.type content-type eg: image/png , .png , png

ctx.response.lastModified eg: ctx.lastModified = new Date()

ctx.response.etag eg: ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');

// 其他

ctx.response.headerSent

ctx.response.vary(field) 等价于 ctx.response.append('Vary', field)

ctx.response.socket

ctx.response.redirect(url, [alt])

ctx.redirect('back');

ctx.redirect('back', '/index.html')

ctx.redirect('/login');

ctx.redirect('http://google.com');

koa 设置cache_koa文档参考相关推荐

  1. C# 设置Word文档保护(加密、解密、权限设置)

    C# 设置Word文档保护(加密.解密.权限设置) 对于一些重要的word文档,出于防止资料被他人查看,或者防止文档被修改的目的,我们在选择文档保护时可以选择文档打开添加密码或者设置文档操作权限等,在 ...

  2. Java 设置PDF文档过期时间(有效时间)

    有些文档具有一定时效性,需在规定时间段内才可阅读查看,针对此类文档,需要设置文档的过期日期.时间等.下面以Java示例演示为例如何给PDF文档设置过期时间.需使用PDF类库, Free Spire.P ...

  3. word如何设置页码?一分钟教你设置Word文档的页码!

    你知道Word怎么设置页码吗?可能你还找不到页码在何处.相信有很多人也会遇到这些类似的问题.如何在Word文档里面的任意一页设置页码呢?word如何设置页码?现在小编就把设置页码的过程和截图分享出来, ...

  4. python语法手册chm-python3.5.2官方帮助文档 参考手册(CHM版)

    python3.5.2官方帮助文档 参考手册(CHM版) python3.5.2官方帮助文档 参考手册(CHM版),欢迎下载! 新语法特性: PEP 492,具有async和await语法的协同程序. ...

  5. python帮助文档中文版下载-python3.5.2官方帮助文档 参考手册(CHM版)

    python3.5.2官方帮助文档 参考手册(CHM版) python3.5.2官方帮助文档 参考手册(CHM版),欢迎下载! 新语法特性: PEP 492,具有async和await语法的协同程序. ...

  6. 文本怎么整体向左缩进_如何设置Word文档的左缩进或者右缩进呢?并在缩进区域输入文字...

    刚刚看到有朋友问了一个非常有意思的问题,他对Word中的文字设置了右缩进,这样在Word的右边就有了一块空白的区域,他想要在这块缩进后留下的空白区域上输入文字,想要知道应该如何操作.在这里要强调一下的 ...

  7. Word2013中怎样设置同一文档内粘贴选项

    在用户编辑或者书写Word文档时,经常碰到需要将前面已经输入过的某一段文字拷贝粘贴到后面中的情况.用户可以根据实际工作需要预设粘贴格式的类型,可以大大减轻操作上的复杂. 在Word 2013文档中,用 ...

  8. python3.6库参考手册_python3.5.2官方帮助文档参考手册(CHM版)

    python3.5.2官方帮助文档 参考手册(CHM版) python3.5.2官方帮助文档 参考手册(CHM版),欢迎下载! 新语法特性: PEP 492,具有async和await语法的协同程序. ...

  9. python3.5中文手册chm_python3.5.2官方帮助文档 参考手册(CHM版)

    python3.5.2官方帮助文档 参考手册(CHM版) python3.5.2官方帮助文档 参考手册(CHM版),欢迎下载! 新语法特性: PEP 492,具有async和await语法的协同程序. ...

最新文章

  1. TransG : A Generative Model for Knowledge Graph Embedding ACL 2016.Berlin, Germany.
  2. 大话 SPA router
  3. python如何做散点图-Python-如何为散点图制作动画?
  4. oc58--Category注意事项
  5. 信息学奥赛一本通 1091:求阶乘的和 / 2026:【例4.12】阶乘和 / OpenJudge NOI 1.5 34
  6. Linux系统调用--getrlimit/setrlimit函数详解
  7. 高级IO--5种及select、poll、epoll的原理、执行以及优缺点
  8. 【es-未解决】es 报错 failed to process cluster event (put-mapping) within 30s
  9. cookie怎样存储数据?
  10. nginx 1.8.0下载
  11. 小白从零开发鸿蒙小游戏(1)“数字华容道”—【深鸿会学习小组学习心得及笔记】
  12. 无法安装冰点还原_冰点还原标准版v8.56.020.5542 ——墨涩网
  13. DNA 测序技术的发展:第三代测序法
  14. MindSpore布道师招募计划,开启AI的信仰之跃
  15. 杭州卧兔:全球品牌出海峰会大咖集聚讲述品牌出海关键要素
  16. 计算机PE不显示硬盘,winpe不显示硬盘?教你轻松搞定pe下不显示硬盘问题
  17. 鸿蒙坐骑九彩祥云,封神演义五大神兽坐骑排名,第一名太出人意料了!
  18. 郭晶晶家的象棋私教,好家伙是个机器人
  19. android 微信摇一摇代码,Android微信摇一摇
  20. Could not resolve

热门文章

  1. IT创业四大“险滩”
  2. Django models新增属性后 迁移报错 KeyError ,--fake解决
  3. 云呐|行政单位固定资产管理制度,单位固定资产管理办法
  4. 软件工程毕设选题推荐 40个高质量计算机毕设项目分享【源码+论文】
  5. 安装系统(win7篇)新手专用
  6. 32位Win7下安装Ubuntu 16.04
  7. MATLAB对图像进行自编top-hat(顶帽变换)程序
  8. viewpage显示服务器图片,照片查看器——ViewPager实现的图片展示控件
  9. 阿里云的域名绑定端口
  10. 2021ICPC上海区域赛DEGKI