forked from koajs/koajs.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
executable file
·990 lines (937 loc) · 54.7 KB
/
index.html
File metadata and controls
executable file
·990 lines (937 loc) · 54.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
<!DOCTYPE html><html><head><title>Koajs - 下一代 Node.js web 框架</title><link rel="stylesheet" href="public/style.css"><link rel="shortcut icon" href="favi.co"><link rel="stylesheet" href="public/icons/css/slate.css"><link rel="stylesheet" href="http://fonts.useso.com/css?family=Italiana&subset=latin"><meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"><meta charset="utf8"><meta name="keywords" content="Koa.js, Koa, Koajs, Node, Web框架, generator, RedNode"><meta name="description" content="Express原班团队打造的下一代 Node.js web 框架, 全新架构, 核心代码精简, 全新的流程书写代码-Koajs"></head><body><section id="top"><div id="menu"><a id="toggle" href="#"><i class="icon-menu"></i></a><ul><li><a href="#introduction">Introduction</a></li><li><a href="#application">Application</a></li><li><a href="#context">Context</a></li><li><a href="#request">Request</a></li><li><a href="#response">Response</a></li><li><a href="#guide">Guide</a></li><li><a href="#links">Links</a></li><li><a href="http://koajs.com" target="_blank">Koajs.com</a></li></ul></div><div id="heading"><div id="logo">Koa</div><div id="tagline">下一代 Node.js web 框架(0.12.0)</div></div></section><section><div class="content"><h1 id="introduction">简介</h1><p>由 Express 原班人马打造的 koa,致力于成为一个更小、更健壮、更富有表现力的 Web 框架。使用 koa 编写 web 应用,通过组合不同的 generator,可以免除重复繁琐的回调函数嵌套,并极大地提升常用错误处理效率。Koa 不在内核方法中绑定任何中间件,它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手。
</p></div></section><section><div class="content"><h1 id="-">安装</h1>
<p> Koa 当前需要 node 0.11.x 并开启 --harmony (或--harmony-generators), 因为它依赖于 ES6 的 generator 特性. 如果你的当前 Node 版本小于 0.11, 可以通过 <a href="https://github.com/visionmedia/n">n</a> (node 版本管理工具) 快速安装 0.11.x</p>
<pre><code>$ npm install -g n
$ n 0.11.12
$ node --harmony my-koa-app.js</code></pre>
<p> 为了方便,可以将 <code>node</code> 设置为默认启动 harmony 模式的别名:</p>
<pre><code>alias node='node --harmony'</code></pre>
<p> 还可以使用 <a href="https://github.com/TooTallNate/gnode">gnode</a> 运行程序, 但执行效率会较低.</p>
<h1 id="application">Application</h1>
<p> Koa 应用是一个包含中间件 generator 方法数组的对象。当请求到来时, 这些方法会以 stack-like 的顺序执行, 从这个角度来看,Koa 和其他中间件系统(比如 Ruby Rack 或者 Connect/Express )非常相似. 然而 Koa 的一大设计理念是: 通过其他底层中间件层提供高级「语法糖」,而不是Koa. 这大大提高了框架的互操作性和健壮性, 并让中间件开发变得简单有趣.</p>
<p> 比如内容协商(content-negotation)、缓存控制(cache freshness)、反向代理(proxy support)重定向等常见功能都由中间件来实现. 将类似常见任务分离给中间件实现, Koa 实现了异常精简的代码. </p>
<p> 一如既往的 Hello world:</p>
<pre><code class="lang-js">var koa = require('koa');
var app = koa();
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);</code></pre>
<p><strong>译者注:</strong> 与普通的 function 不同,generator functions 以 <code>function*</code> 声明。以这种关键词声明的函数支持 <code>yield</code></p>
<h2 id="-cascading-">代码级联(Cascading)</h2>
<p> Koa 中间件以一种更加传统的方式级联起来, 跟你在其他系统或工具中碰到的方式非常相似。
然而在以往的 Node 开发中, 级联是通过回调实现的, 想要开发用户友好的代码是非常困难的,
Koa 借助 generators 实现了真正的中间件架构, 与 Connect 实现中间件的方法相对比,Koa 的做法不是简单的将控制权依次移交给一个又一个的方法直到某个结束,Koa 执行代码的方式有点像回形针,用户请求通过中间件,遇到 <code>yield next</code> 关键字时,会被传递到下游中间件(downstream),在 <code>yield next</code> 捕获不到下一个中间件时,逆序返回继续执行代码(upstream)。</p>
<p> 下边这个简单返回 Hello World 的例子可以很好说明 Koa 的中间件机制:一开始,请求经过 x-response-time 和 logging 中间件,记录了请求的开始时间,然后将控制权 yield 给 response 中间件. 当一个中间件执行 <code>yield next</code>时,该方法会暂停执行并把控制权传递给下一个中间件,当没有下一个中间件执行 downstream 的时候,代码将会逆序执行所有流过中间件的 upstream 代码。</p>
<pre><code class="lang-js">var koa = require('koa');
var app = koa();
// x-response-time
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
// logger
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
// response
app.use(function *(){
this.body = 'Hello World';
});
app.listen(3000);</code></pre>
<pre><code>.middleware1 {
// (1) do some stuff
.middleware2 {
// (2) do some other stuff
.middleware3 {
// (3) NO next yield !
// this.body = 'hello world'
}
// (4) do some other stuff later
}
// (5) do some stuff lastest and return
}</code></pre>
<p>上方的伪代码中标注了中间件的执行顺序,看起来是不是有点像 ruby 执行代码块(block)时 yield 的表现了?也许这能帮助你更好的理解 koa 运作的方式。</p>
<p><strong>译者注:</strong> 更加形象的图可以参考 <a href="https://docs.djangoproject.com/en/1.6/topics/http/middleware/">Django Middleware</a></p>
<p><img src="https://raw.github.com/fengmk2/koa-guide/master/onion.png" alt="onion.png"></p>
<h2 id="-settings-">配置(Settings)</h2>
<p>应用配置是 app 实例的属性, 目前支持以下配置:</p>
<ul>
<li>app.name 应用名称</li>
<li>app.env 默认是 <strong>NODE_ENV</strong> 或者 "development"</li>
<li>app.proxy 决定了哪些 <code>proxy header</code> 参数会被加到信任列表中</li>
<li>app.subdomainOffset 被忽略的 <code>.subdomains</code> 列表,详见下方 api</li>
</ul>
<h2 id="app-listen-">app.listen(...)</h2>
<p> 一个 Koa 应用跟 HTTP server 不是 1-to-1 关系, 一个或多个 Koa 应用可以被加载到一块
组成一个更大的包含一个 HTTP server 的应用.</p>
<p> 该方法创建并返回一个 http server, 并且支持传递固定参数
<code>Server#listen()</code>. 具体参数可查看 <a href="http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback">nodejs.org</a>. 如下为一个监听 <code>3000</code> 端口的简单应用:</p>
<pre><code class="lang-js">var koa = require('koa');
var app = koa();
app.listen(3000);</code></pre>
<p> 方法 <code>app.listen(...)</code> 是一个语法糖, 等价于:</p>
<pre><code class="lang-js">var http = require('http');
var koa = require('koa');
var app = koa();
http.createServer(app.callback()).listen(3000);</code></pre>
<p> 这意味着你可以同时支持 HTTP 和 HTTPS, 或在多个地址上使用同一个 app.</p>
<pre><code class="lang-js">var http = require('http');
var koa = require('koa');
var app = koa();
http.createServer(app.callback()).listen(3000);
http.createServer(app.callback()).listen(3001);</code></pre>
<h2 id="app-callback-">app.callback()</h2>
<p> 返回一个回调方法能用于 <code>http.createServer()</code> 来处理请求,也可以将这个回调函数挂载到 Connect/Express 应用上。</p>
<h2 id="app-use-function-">app.use(function)</h2>
<p> 将给定的 function 当做中间件加载到应用中,详见 <a href="https://github.com/koajs/koa/wiki#middleware">中间件</a> </p>
<h2 id="app-keys-">app.keys=</h2>
<p> 设置 Cookie 签名密钥。</p>
<p> 这些值会被传递给 <a href="https://github.com/jed/keygrip">KeyGrip</a> 如果你想自己生成一个实例,也可以这样:</p>
<pre><code class="lang-js">app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');</code></pre>
<p> 注意,签名密钥只在配置项 <code>signed</code> 参数为真是才会生效:</p>
<pre><code class="lang-js">this.cookies.set('name', 'tobi', { signed: true });</code></pre>
<h2 id="-error-handling-">错误处理(Error Handling)</h2>
<p> 除非应用执行环境(<strong>NODE_ENV</strong>)被配置为 <code>"test"</code>,Koa 都将会将所有错误信息输出到 stderr. 如果想自定义错误处理逻辑, 可以定义一个「错误事件」来监听 Koa app 中发生的错误:</p>
<pre><code class="lang-js">app.on('error', function(err){
log.error('server error', err);
});</code></pre>
<p> 当 req/res 周期中出现任何错误且无法响应客户端时,Koa 会把 <code>Context</code>(上下文) 实例作为第二个参数传递给 error 事件:</p>
<pre><code class="lang-js">app.on('error', function(err, ctx){
log.error('server error', err, ctx);
});</code></pre>
<p> 如果有错误发生, 并且还能响应客户端(即没有数据被写入到 socket), Koa 会返回 500 "Internal Server Error".
这两种情况都会触发 app-level 的 error 事件, 用于 logging.</p>
</div></section><section><div class="content"><h1 id="context">Context</h1>
<p> Koa 的 Context 把 node 的 request, response 对象封装进一个单独对象, 并提供许多开发 web 应用和 APIs 有用的方法.
那些在 HTTP server 开发中使用非常频繁操作, 直接在 Koa 里实现,
而不是放在更高层次的框架, 这样中间件就不需要重复实现这些通用的功能.</p>
<p> <em>每个</em> 请求会创建自己的 <code>Context</code> 实例, 在中间件中作为 receiver 引用, 或通过 <code>this</code> 标示符引用. 如.</p>
<pre><code class="lang-js">app.use(function *(){
this; // is the Context
this.request; // is a koa Request
this.response; // is a koa Response
});</code></pre>
<p>Context 的许多访问器和方法直接委托为他们的 <code>ctx.request</code> 或 <code>ctx.response</code> 的
等价方法, 用于访问方便, 是完全相同的. 比如<code>ctx.type</code> 和 <code>ctx.length</code>
委托与 <code>response</code> 对象, <code>ctx.path</code> 和 <code>ctx.method</code> 委托与 <code>request</code>.</p>
<h2 id="api">API</h2>
<p> <code>Context</code> 详细方法和访问器.</p>
<h3 id="ctx-req">ctx.req</h3>
<p> Node 的 <code>request</code> 对象.</p>
<h3 id="ctx-res">ctx.res</h3>
<p> Node 的 <code>response</code> 对象.</p>
<p> 绕开 Koa 的 response 处理 是 <strong>不支持</strong>的. 避免使用如下 node 属性:</p>
<ul>
<li><code>res.statusCode</code></li>
<li><code>res.writeHead()</code></li>
<li><code>res.write()</code></li>
<li><code>res.end()</code></li>
</ul>
<h3 id="ctx-request">ctx.request</h3>
<p> koa <code>Request</code> 对象.</p>
<h3 id="ctx-response">ctx.response</h3>
<p> koa <code>Response</code> 对象.</p>
<h3 id="ctx-app">ctx.app</h3>
<p> 应用实例引用.</p>
<h3 id="ctx-cookies-get-name-options-">ctx.cookies.get(name, [options])</h3>
<p> 获取名为 <code>name</code> 带有 <code>options</code> 的 cookie:</p>
<ul>
<li><code>signed</code> 请求的 cookie 应该是被 signed</li>
</ul>
<p>koa 使用 <a href="https://github.com/jed/cookies">cookies</a> 模块, options 被直接传递过去.</p>
<h3 id="ctx-cookies-set-name-value-options-">ctx.cookies.set(name, value, [options])</h3>
<p> 设置 cookie <code>name</code> 为 <code>value</code> 带有 <code>options</code>:</p>
<ul>
<li><code>signed</code> sign cookie 值</li>
<li><code>expires</code> cookie 过期 <code>Date</code></li>
<li><code>path</code> cookie 路径, 默认 <code>/'</code></li>
<li><code>domain</code> cookie 域名</li>
<li><code>secure</code> secure cookie</li>
<li><code>httpOnly</code> server 才能访问 cookie, 默认 <strong>true</strong> </li>
</ul>
<p>koa 使用 <a href="https://github.com/jed/cookies">cookies</a> 模块, options 被直接传递过去.</p>
<h3 id="ctx-throw-msg-status-properties-">ctx.throw([msg], [status], [properties])</h3>
<p> Helper 方法, 抛出包含 <code>.status</code> 属性的错误, 默认为 <code>500</code>. 该方法让 Koa 能够合适的响应.
并且支持如下组合:</p>
<pre><code class="lang-js">this.throw(403)
this.throw('name required', 400)
this.throw(400, 'name required')
this.throw('something exploded')</code></pre>
<p> 例如 <code>this.throw('name required', 400)</code> 等价于:</p>
<pre><code class="lang-js">var err = new Error('name required');
err.status = 400;
throw err;</code></pre>
<p> 注意这些是 user-level 的错误, 被标记为 <code>err.expose</code>, 即这些消息可以用于 client 响应,
而不是 error message 的情况, 因为你不想泄露失败细节.</p>
<p> 你可以传递一个 <code>properties</code> 对象, 该对象会被合并到 error 中, 这在修改传递给上游中间件的机器友好错误时非常有用</p>
<pre><code class="lang-js">this.throw(401, 'access_denied', { user: user });
this.throw('access_denied', { user: user });</code></pre>
<p>koa 使用 <a href="https://github.com/jshttp/http-errors">http-errors</a> 创建错误对象.</p>
<h3 id="ctx-assert-value-msg-status-properties-">ctx.assert(value, [msg], [status], [properties])</h3>
<p> 抛出错误的 Helper 方法, 跟 <code>.throw()</code> 相似
当 <code>!value</code>. 跟 node 的 <a href="http://nodejs.org/api/assert.html">assert()</a>
方法相似.</p>
<pre><code class="lang-js">this.assert(this.user, 401, 'User not found. Please login!');</code></pre>
<p>koa 使用 <a href="https://github.com/jshttp/http-assert">http-assert</a> 实现断言.</p>
<h3 id="ctx-respond">ctx.respond</h3>
<p> 如不想使用 koa 内置的 response 处理方法, 可以设置 <code>this.respond = false;</code>. 这时你可以自己设置 <code>res</code> 对象.</p>
<p> 注意这样使用是不被 Koa 支持的. 这样有可能会破坏 Koa 的中间件和 Koa 本身内部功能. 这种用法只是作为一种 hack 方式, 给那些想在 Koa 中间件和方法内使用传统的<code>fn(req, res)</code> 一种方式</p>
<h2 id="request-">Request 别名</h2>
<p> 如下访问器和别名同 <a href="#request">Request</a> 等价:</p>
<ul>
<li><code>ctx.header</code></li>
<li><code>ctx.headers</code></li>
<li><code>ctx.method</code></li>
<li><code>ctx.method=</code></li>
<li><code>ctx.url</code></li>
<li><code>ctx.url=</code></li>
<li><code>ctx.originalUrl</code></li>
<li><code>ctx.path</code></li>
<li><code>ctx.path=</code></li>
<li><code>ctx.query</code></li>
<li><code>ctx.query=</code></li>
<li><code>ctx.querystring</code></li>
<li><code>ctx.querystring=</code></li>
<li><code>ctx.host</code></li>
<li><code>ctx.hostname</code></li>
<li><code>ctx.fresh</code></li>
<li><code>ctx.stale</code></li>
<li><code>ctx.socket</code></li>
<li><code>ctx.protocol</code></li>
<li><code>ctx.secure</code></li>
<li><code>ctx.ip</code></li>
<li><code>ctx.ips</code></li>
<li><code>ctx.subdomains</code></li>
<li><code>ctx.is()</code></li>
<li><code>ctx.accepts()</code></li>
<li><code>ctx.acceptsEncodings()</code></li>
<li><code>ctx.acceptsCharsets()</code></li>
<li><code>ctx.acceptsLanguages()</code></li>
<li><code>ctx.get()</code></li>
</ul>
<h2 id="response-">Response 别名</h2>
<p> 如下访问器和别名同 <a href="#response">Response</a> 等价:</p>
<ul>
<li><code>ctx.body</code></li>
<li><code>ctx.body=</code></li>
<li><code>ctx.status</code></li>
<li><code>ctx.status=</code></li>
<li><code>ctx.length=</code></li>
<li><code>ctx.length</code></li>
<li><code>ctx.type=</code></li>
<li><code>ctx.type</code></li>
<li><code>ctx.headerSent</code></li>
<li><code>ctx.redirect()</code></li>
<li><code>ctx.attachment()</code></li>
<li><code>ctx.set()</code></li>
<li><code>ctx.remove()</code></li>
<li><code>ctx.lastModified=</code></li>
<li><code>ctx.etag=</code></li>
</ul>
</div></section><section><div class="content"><h1 id="request">Request</h1>
<p> Koa <code>Request</code> 对象是 node 普通 request 对象之上的抽象, 提供了日常 HTTP server 中更多有用的功能.</p>
<h2 id="api">API</h2>
<h3 id="req-header">req.header</h3>
<p> 请求头对象.</p>
<h3 id="req-headers">req.headers</h3>
<p> req.header 的别名</p>
<h3 id="req-method">req.method</h3>
<p> 请求方法.</p>
<h3 id="req-method-">req.method=</h3>
<p> 设置请求方法, 实现中间件时非常有用, 例如 <code>methodOverride()</code>.</p>
<h3 id="req-length">req.length</h3>
<p> 将请求的 Content-Length 返回为数字, 或 <code>undefined</code>.</p>
<h3 id="req-url">req.url</h3>
<p> 获取请求 URL.</p>
<h3 id="req-url-">req.url=</h3>
<p> 设置请求 URL, 在 rewrites 时有用.</p>
<h3 id="req-originalurl">req.originalUrl</h3>
<p> 获取 original URL.</p>
<h3 id="req-path">req.path</h3>
<p> 获取请求 pathname.</p>
<h3 id="req-path-">req.path=</h3>
<p> 设置请求 pathname, 如果有 query-string 则保持不变.</p>
<h3 id="req-querystring">req.querystring</h3>
<p> 获取原始 query string, 不包含 <code>?</code>.</p>
<h3 id="req-querystring-">req.querystring=</h3>
<p> 设置 query string.</p>
<h3 id="req-search">req.search</h3>
<p> 获取原始 query string, 包含 <code>?</code>.</p>
<h3 id="req-search-">req.search=</h3>
<p> 设置 query string.</p>
<h3 id="req-host">req.host</h3>
<p> 获取 host, 不包含端口号. 当 <code>app.proxy</code> 为 <strong>true</strong> 时支持 <code>X-Forwarded-Host</code>, 否者就使用 <code>Host</code>. </p>
<h3 id="req-hostname">req.hostname</h3>
<p> 获取 hostname 如果有的话. 当 <code>app.proxy</code> 设为 <strong>true</strong> 时支持 <code>X-Forwarded-Host</code>, 否则直接使用 <code>Host</code>.</p>
<h3 id="req-type">req.type</h3>
<p> 获取请求 <code>Content-Type</code> 字段, 不包含参数, 如 "charset".</p>
<pre><code class="lang-js">var ct = this.type;
// => "image/png"</code></pre>
<h3 id="req-charset">req.charset</h3>
<p> 获取请求 charset, 没有返回 <code>undefined</code></p>
<pre><code class="lang-js">this.request.charset
// => "utf-8"</code></pre>
<h3 id="req-query">req.query</h3>
<p> 获取解析后的 query-string, 如果没有返回空对象. 注意: 该方法不支持嵌套解析.</p>
<p> 例如 "color=blue&size=small":</p>
<pre><code class="lang-js">{
color: 'blue',
size: 'small'
}</code></pre>
<h3 id="req-query-">req.query=</h3>
<p> 根据给定的对象设置 query-string. 注意: 该方法不支持嵌套对象.</p>
<pre><code class="lang-js">this.query = { next: '/login' };</code></pre>
<h3 id="req-fresh">req.fresh</h3>
<p> 检查请求缓存是否是 "fresh" 的, 即内容没有发生变化. 该方法用于在<code>If-None-Match</code> / <code>ETag</code>, <code>If-Modified-Since</code>, <code>Last-Modified</code> 之间进行缓存 negotiation. 这个应该在设置过这些响应 hearder 后会用到.</p>
<pre><code class="lang-js">this.set('ETag', '123');
// cache is ok
if (this.fresh) {
this.status = 304;
return;
}
// cache is stale
// fetch new data
this.body = yield db.find('something');</code></pre>
<h3 id="req-stale">req.stale</h3>
<p> 相反与 <code>req.fresh</code>.</p>
<h3 id="req-protocol">req.protocol</h3>
<p> 返回请求协议, "https" 或 "http". 当 <code>app.proxy</code> 为 <strong>true</strong> 时支持 <code>X-Forwarded-Proto</code>.</p>
<h3 id="req-secure">req.secure</h3>
<p> 简化版 <code>this.protocol == "https"</code> 用于检查请求是否通过 TLS 发送.</p>
<h3 id="req-ip">req.ip</h3>
<p> 请求 IP 地址. 当 <code>app.proxy</code> 为 <strong>true</strong> 时支持 <code>X-Forwarded-Proto</code>.</p>
<h3 id="req-ips">req.ips</h3>
<p> 当 <code>X-Forwarded-For</code> 存在并且 <code>app.proxy</code> 开启会返回一个有序(upstream -> downstream)的 ip 数组.
否则返回空数组.</p>
<h3 id="req-subdomains">req.subdomains</h3>
<p> 以数组形式返回子域名.</p>
<p> 子域名是 host 逗号分隔主域名前面的部分. 默认主域名是 host 的最后两部分. 可以通过设置 <code>app.subdomainOffset</code> 调整.</p>
<p> 例如, 架设域名是 "tobi.ferrets.example.com":
如果 <code>app.subdomainOffset</code> 没有设置, this.subdomains 为 <code>["ferrets", "tobi"]</code>.
如果 <code>app.subdomainOffset</code> 设为 3, this.subdomains 为 <code>["tobi"]</code>.</p>
<h3 id="req-is-type-">req.is(type)</h3>
<p> 检查请求是否包含 "Content-Type" 字段, 并且包含当前已知的 mime 'type'.
如果没有请求 body, 返回 <code>undefined</code>.
如果没有字段, 或不包含, 返回 <code>false</code>.
否则返回包含的 content-type.</p>
<pre><code class="lang-js">// With Content-Type: text/html; charset=utf-8
this.is('html'); // => 'html'
this.is('text/html'); // => 'text/html'
this.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
this.is('json', 'urlencoded'); // => 'json'
this.is('application/json'); // => 'application/json'
this.is('html', 'application/*'); // => 'application/json'
this.is('html'); // => false</code></pre>
<p> 例如, 如果你想确保指定的路由只返回图片.</p>
<pre><code class="lang-js">if (this.is('image/*')) {
// process
} else {
this.throw(415, 'images only!');
}</code></pre>
<h3 id="content-negotiation">Content Negotiation</h3>
<p> Koa 的 <code>请求</code> 对象包含有用的内容 negotiation 方法, 这些方法由<a href="http://github.com/expressjs/accepts">accepts</a> 和 <a href="https://github.com/federomero/negotiator">negotiator</a> 提供, 主要包括:</p>
<ul>
<li><code>req.accepts(types)</code></li>
<li><code>req.acceptsEncodings(types)</code></li>
<li><code>req.acceptsCharsets(charsets)</code></li>
<li><p><code>req.acceptsLanguages(langs)</code></p>
<p>如果没有提供 types, 将会返回所有支持的 type</p>
<p>如果提供多个 type, 将会返回最符合的那个, 如果没有符合的类型, 将会返回 false, 这时你应该响应 <code>406 "Not Acceptable"</code> 给客户端</p>
<p>如果没有 accept headers, 即被认为可以接受任何 type, 会返回第一个 type, 这时提供的 type 顺序会非常重要</p>
</li>
</ul>
<h3 id="req-accepts-types-">req.accepts(types)</h3>
<p> 检查给定的 <code>type(s)</code> 是否 acceptable, 如果是, 则返回最佳的匹配, 否则 <code>false</code>,
这时应该响应 406 "Not Acceptable".</p>
<p> <code>type</code> 值应该是一个或多个 mime 字符串, 例如 "application/json", 扩展名如 "json", 或数组 <code>["json", "html", "text/plain"]</code>.
如果给定一个 list 或 array, 会返回最佳(<em>best</em>)匹配项.</p>
<p> 如果请求 client 没有发送 <code>Accept</code> header, 会返回第一个 <code>type</code>.</p>
<pre><code class="lang-js">// Accept: text/html
this.accepts('html');
// => "html"
// Accept: text/*, application/json
this.accepts('html');
// => "html"
this.accepts('text/html');
// => "text/html"
this.accepts('json', 'text');
// => "json"
this.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
this.accepts('image/png');
this.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
this.accepts(['html', 'json']);
this.accepts('html', 'json');
// => "json"
// No Accept header
this.accepts('html', 'json');
// => "html"
this.accepts('json', 'html');
// => "json"</code></pre>
<p> <code>this.accepts()</code> 可以被多次调用, 或使用在 switch.</p>
<pre><code class="lang-js">switch (this.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: this.throw(406, 'json, html, or text only');
}</code></pre>
<h3 id="req-acceptsencodings-encodings-">req.acceptsEncodings(encodings)</h3>
<p> 检查 <code>encodings</code> 是否被接受, 如果是返回最佳匹配, 否则返回 <code>identity</code>.</p>
<pre><code class="lang-js">// Accept-Encoding: gzip
this.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"
this.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"</code></pre>
<p> 如果没有传递参数, 会返回所有可接受的 encodings 数组.</p>
<pre><code class="lang-js">// Accept-Encoding: gzip, deflate
this.acceptsEncodings();
// => ["gzip", "deflate", "identity"]</code></pre>
<p> 注意 <code>identity</code> 编码 (等同于没有编码) 不会被接受, 如果客户端明确的发送了 <code>identity;q=0</code>. 虽然这种情况很少发生, 但你需要手动处理该方法返回
<code>false</code> 情况.</p>
<h3 id="req-acceptscharsets-charsets-">req.acceptsCharsets(charsets)</h3>
<p> 检查 <code>charsets</code> 是否被接受, 如果是返回最佳匹配, 否则 <code>undefined</code>.</p>
<pre><code class="lang-js">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
this.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"</code></pre>
<p> 如果没有传递参数, 会返回所有可接受 charsets 数组.</p>
<pre><code class="lang-js">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]</code></pre>
<h3 id="req-acceptslanguages-langs-">req.acceptsLanguages(langs)</h3>
<p> 检查 <code>langs</code> 是否被接受, 如果是返回最佳匹配, 否则返回 <code>undefined</code>.</p>
<pre><code class="lang-js">// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages('es', 'en');
// => "es"
this.acceptsLanguages(['en', 'es']);
// => "es"</code></pre>
<p> 如果没有传递参数, 会返回所有可接受的 lang 数组.</p>
<pre><code class="lang-js">// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages();
// => ["es", "pt", "en"]</code></pre>
<h3 id="req-idempotent">req.idempotent</h3>
<p> 判断请求是否是 idempotent.</p>
<h3 id="req-socket">req.socket</h3>
<p> 返回请求 socket.</p>
<h3 id="req-get-field-">req.get(field)</h3>
<p> 返回请求 header.</p>
<h1 id="request">Request</h1>
<p> Koa <code>Request</code> 对象是 node 普通 request 对象之上的抽象, 提供了日常 HTTP server 中有用的功能.</p>
<h2 id="api">API</h2>
<h3 id="req-header">req.header</h3>
<p> 请求头对象.</p>
<h3 id="req-method">req.method</h3>
<p> 请求方法.</p>
<h3 id="req-method-">req.method=</h3>
<p> 设置请求方法, 实现中间件时非常有用, 例如 <code>methodOverride()</code>.</p>
<h3 id="req-length">req.length</h3>
<p> 将请求的 Content-Length 返回为数字, 或 <code>undefined</code>.</p>
<h3 id="req-url">req.url</h3>
<p> 获取请求 URL.</p>
<h3 id="req-url-">req.url=</h3>
<p>设置请求 URL, 在 rewrites 时有用.</p>
<h3 id="req-path">req.path</h3>
<p> 获取请求 pathname.</p>
<h3 id="req-path-">req.path=</h3>
<p> 设置请求 pathname, 如果有 query-string 则保持不变.</p>
<h3 id="req-querystring">req.querystring</h3>
<p> 获取原始 query string, 不包含 <code>?</code>.</p>
<h3 id="req-querystring-">req.querystring=</h3>
<p> 设置 query string.</p>
<h3 id="req-search">req.search</h3>
<p> 获取原始 query string, 包含 <code>?</code>.</p>
<h3 id="req-search-">req.search=</h3>
<p> 设置 query string.</p>
<h3 id="req-host">req.host</h3>
<p> 获取 host, 不包含端口号. 当 <code>app.proxy</code> 为 <strong>true</strong> 时支持 <code>X-Forwarded-Host</code>, 否者就使用 <code>Host</code>. </p>
<h3 id="req-host-">req.host=</h3>
<p> 设置 <code>Host</code> 头字段.</p>
<h3 id="req-type">req.type</h3>
<p> 获取请求 <code>Content-Type</code> 字段, 不包含参数, 如 "charset".</p>
<pre><code class="lang-js">var ct = this.type;
// => "image/png"</code></pre>
<h3 id="req-charset">req.charset</h3>
<p> 获取请求 charset, 没有返回 <code>undefined</code></p>
<h3 id="req-query">req.query</h3>
<p> 获取解析后的 query-string, 如果没有返回空对象. 注意: 该方法不支持嵌套解析.</p>
<p> 例如 "color=blue&size=small":</p>
<pre><code class="lang-js">{
color: 'blue',
size: 'small'
}</code></pre>
<h3 id="req-query-">req.query=</h3>
<p> 根据给定的对象设置 query-string. 注意: 该方法不支持嵌套对象.</p>
<pre><code class="lang-js">this.query = { next: '/login' };</code></pre>
<h3 id="req-fresh">req.fresh</h3>
<p> 检查请求缓存是否是 "fresh" 的, 即内容没有发生变化. 该方法用于在<code>If-None-Match</code> / <code>ETag</code>, <code>If-Modified-Since</code>, <code>Last-Modified</code> 之间进行缓存 negotiation. 这个应该在设置过这些响应 hearder 后会用到.</p>
<pre><code class="lang-js">this.set('ETag', '123');
// cache is ok
if (this.fresh) {
this.status = 304;
return;
}
// cache is stale
// fetch new data
this.body = yield db.find('something');</code></pre>
<h3 id="req-stale">req.stale</h3>
<p> 相反与 <code>req.fresh</code>.</p>
<h3 id="req-protocol">req.protocol</h3>
<p> 返回请求协议, "https" 或 "http". 当 <code>app.proxy</code> 为 <strong>true</strong> 时支持 <code>X-Forwarded-Proto</code>.</p>
<h3 id="req-secure">req.secure</h3>
<p> 简化版 <code>this.protocol == "https"</code> 用于检查请求是否通过 TLS 发送.</p>
<h3 id="req-ip">req.ip</h3>
<p> 请求 IP 地址. 当 <code>app.proxy</code> 为 <strong>true</strong> 时支持 <code>X-Forwarded-Proto</code>.</p>
<h3 id="req-ips">req.ips</h3>
<p> 当 <code>X-Forwarded-For</code> 存在并且 <code>app.proxy</code> 开启会返回一个有序(upstream -> downstream)的 ip 数组.
否则返回空数组.</p>
<h3 id="req-subdomains">req.subdomains</h3>
<p> 以数组形式返回子域名.</p>
<p> 子域名是 host 逗号分隔主域名前面的部分. 默认主域名是 host 的最后两部分. 可以通过设置 <code>app.subdomainOffset</code> 调整.</p>
<p> 例如, 架设域名是 "tobi.ferrets.example.com":
如果 <code>app.subdomainOffset</code> 没有设置, this.subdomains 为 <code>["ferrets", "tobi"]</code>.
如果 <code>app.subdomainOffset</code> 设为 3, this.subdomains 为 <code>["tobi"]</code>.</p>
<h3 id="req-is-type-">req.is(type)</h3>
<p> 检查请求是否包含 "Content-Type" 字段, 并且包含当前已知的 mime 'type'.
如果没有请求 body, 返回 <code>undefined</code>.
如果没有字段, 或不包含, 返回 <code>false</code>.
否则返回包含的 content-type.</p>
<pre><code class="lang-js">// With Content-Type: text/html; charset=utf-8
this.is('html'); // => 'html'
this.is('text/html'); // => 'text/html'
this.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
this.is('json', 'urlencoded'); // => 'json'
this.is('application/json'); // => 'application/json'
this.is('html', 'application/*'); // => 'application/json'
this.is('html'); // => false</code></pre>
<p> 例如, 如果你想确保指定的路由只返回图片.</p>
<pre><code class="lang-js">if (this.is('image/*')) {
// process
} else {
this.throw(415, 'images only!');
}</code></pre>
<h3 id="req-accepts-types-">req.accepts(types)</h3>
<p> 检查给定的 <code>type(s)</code> 是否 acceptable, 如果是, 则返回最佳的匹配, 否则 <code>false</code>,
这时应该响应 406 "Not Acceptable".</p>
<p> <code>type</code> 值应该是一个或多个 mime 字符串, 例如 "application/json", 扩展名如 "json", 或数组 <code>["json", "html", "text/plain"]</code>.
如果给定一个 list 或 array, 会返回最佳(<em>best</em>)匹配项.</p>
<p> 如果请求 client 没有发送 <code>Accept</code> header, 会返回第一个 <code>type</code>.</p>
<pre><code class="lang-js">// Accept: text/html
this.accepts('html');
// => "html"
// Accept: text/*, application/json
this.accepts('html');
// => "html"
this.accepts('text/html');
// => "text/html"
this.accepts('json', 'text');
// => "json"
this.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
this.accepts('image/png');
this.accepts('png');
// => undefined
// Accept: text/*;q=.5, application/json
this.accepts(['html', 'json']);
this.accepts('html', 'json');
// => "json"</code></pre>
<p> <code>this.accepts()</code> 可以被多次调用, 或使用在 switch.</p>
<pre><code class="lang-js">switch (this.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: this.throw(406);
}</code></pre>
<h3 id="req-acceptsencodings-encodings-">req.acceptsEncodings(encodings)</h3>
<p> 检查 <code>encodings</code> 是否被接受, 如果是返回最佳匹配, 否则返回 <code>identity</code>.</p>
<pre><code class="lang-js">// Accept-Encoding: gzip
this.acceptsEncodings('gzip', 'deflate');
// => "gzip"
this.acceptsEncodings(['gzip', 'deflate']);
// => "gzip"</code></pre>
<p> 如果没有传递参数, 会返回所有可接受的 encodings 数组.</p>
<pre><code class="lang-js">// Accept-Encoding: gzip, deflate
this.acceptsEncodings();
// => ["gzip", "deflate"]</code></pre>
<h3 id="req-acceptscharsets-charsets-">req.acceptsCharsets(charsets)</h3>
<p> 检查 <code>charsets</code> 是否被接受, 如果是返回最佳匹配, 否则 <code>undefined</code>.</p>
<pre><code class="lang-js">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
this.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"</code></pre>
<p> 如果没有传递参数, 会返回所有可接受 charsets 数组.</p>
<pre><code class="lang-js">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]</code></pre>
<h3 id="req-acceptslanguages-langs-">req.acceptsLanguages(langs)</h3>
<p> 检查 <code>langs</code> 是否被接受, 如果是返回最佳匹配, 否则返回 <code>undefined</code>.</p>
<pre><code class="lang-js">// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages('es', 'en');
// => "es"
this.acceptsLanguages(['en', 'es']);
// => "es"</code></pre>
<p> 如果没有传递参数, 会返回所有可接受的 lang 数组.</p>
<pre><code class="lang-js">// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages();
// => ["es", "pt", "en"]</code></pre>
<h3 id="req-idempotent">req.idempotent</h3>
<p> 判断请求是否是 idempotent.</p>
<h3 id="req-socket">req.socket</h3>
<p> 返回请求 socket.</p>
<h3 id="req-get-field-">req.get(field)</h3>
<p> 返回请求 header.</p>
</div></section><section><div class="content"><h1 id="response">Response</h1>
<p> Koa <code>Response</code> 对象是 node 普通 request 对象之上的抽象, 提供了日常 HTTP server 中有用的功能.</p>
<h2 id="api">API</h2>
<h3 id="res-header">res.header</h3>
<p> 响应 header 对象.</p>
<h3 id="res-socket">res.socket</h3>
<p> 请求socket</p>
<h3 id="res-status">res.status</h3>
<p> 返回响应状态. 默认 <code>res.status</code> 没有值, 而不是像 node 的 <code>res.statusCode</code> 默认为 <code>200</code>.</p>
<h3 id="res-status-">res.status=</h3>
<p> 使用状态码或不区分大小写的字符串设置响应状态:</p>
<ul>
<li>100 "continue"</li>
<li>101 "switching protocols"</li>
<li>102 "processing"</li>
<li>200 "ok"</li>
<li>201 "created"</li>
<li>202 "accepted"</li>
<li>203 "non-authoritative information"</li>
<li>204 "no content"</li>
<li>205 "reset content"</li>
<li>206 "partial content"</li>
<li>207 "multi-status"</li>
<li>300 "multiple choices"</li>
<li>301 "moved permanently"</li>
<li>302 "moved temporarily"</li>
<li>303 "see other"</li>
<li>304 "not modified"</li>
<li>305 "use proxy"</li>
<li>307 "temporary redirect"</li>
<li>400 "bad request"</li>
<li>401 "unauthorized"</li>
<li>402 "payment required"</li>
<li>403 "forbidden"</li>
<li>404 "not found"</li>
<li>405 "method not allowed"</li>
<li>406 "not acceptable"</li>
<li>407 "proxy authentication required"</li>
<li>408 "request time-out"</li>
<li>409 "conflict"</li>
<li>410 "gone"</li>
<li>411 "length required"</li>
<li>412 "precondition failed"</li>
<li>413 "request entity too large"</li>
<li>414 "request-uri too large"</li>
<li>415 "unsupported media type"</li>
<li>416 "requested range not satisfiable"</li>
<li>417 "expectation failed"</li>
<li>418 "i'm a teapot"</li>
<li>422 "unprocessable entity"</li>
<li>423 "locked"</li>
<li>424 "failed dependency"</li>
<li>425 "unordered collection"</li>
<li>426 "upgrade required"</li>
<li>428 "precondition required"</li>
<li>429 "too many requests"</li>
<li>431 "request header fields too large"</li>
<li>500 "internal server error"</li>
<li>501 "not implemented"</li>
<li>502 "bad gateway"</li>
<li>503 "service unavailable"</li>
<li>504 "gateway time-out"</li>
<li>505 "http version not supported"</li>
<li>506 "variant also negotiates"</li>
<li>507 "insufficient storage"</li>
<li>509 "bandwidth limit exceeded"</li>
<li>510 "not extended"</li>
<li>511 "network authentication required"</li>
</ul>
<p><strong>注意</strong>: 不用担心没法记住这些状态码, 如果设置错误, 会有异常抛出, 并列出该状态码表,
从而帮助修改.</p>
<h3 id="res-length-">res.length=</h3>
<p> 设置响应 Content-Length.</p>
<h3 id="res-length">res.length</h3>
<p> 如果 Content-Length 存在返回相应数值, 或通过 <code>res.body</code> 计算得出, 否则返回 <code>undefined</code>.</p>
<h3 id="res-body">res.body</h3>
<p> 返回响应内容.</p>
<h3 id="res-body-">res.body=</h3>
<p>设置响应内容为如下值:</p>
<ul>
<li><code>string</code> written</li>
<li><code>Buffer</code> written</li>
<li><code>Stream</code> piped</li>
<li><code>Object</code> json-stringified</li>
<li><p><code>null</code> no content response</p>
<p>如果 <code>res.status</code> 没有设置, Koa 会自动设定 status 为 <code>200</code> 或 <code>204</code>.</p>
</li>
</ul>
<h4 id="string">String</h4>
<p> Content-Type 默认设置为 text/html 或 text/plain, 两个的编码都是 utf-8. Content-Length 同样会被设置.</p>
<h4 id="buffer">Buffer</h4>
<p> Content-Type 默认设置为 application/octet-stream, 并设置 Content-Length.</p>
<h4 id="stream">Stream</h4>
<p> Content-Type 默认设置为 application/octet-stream.</p>
<h4 id="object">Object</h4>
<p> Content-Type 默认设置为 to application/json.</p>
<h3 id="res-get-field-">res.get(field)</h3>
<p> 获取响应头部字段值, <code>field</code> 区分大小写.</p>
<pre><code class="lang-js">var etag = this.get('ETag');</code></pre>
<h3 id="res-set-field-value-">res.set(field, value)</h3>
<p> 设置响应头部字段 <code>field</code> 为 <code>value</code>:</p>
<pre><code class="lang-js">this.set('Cache-Control', 'no-cache');</code></pre>
<h3 id="res-set-fields-">res.set(fields)</h3>
<p> 使用对象同时设置多个响应头 <code>fields</code></p>
<pre><code class="lang-js">this.set({
'Etag': '1234',
'Last-Modified': date
});</code></pre>
<h3 id="res-remove-field-">res.remove(field)</h3>
<p> 删除头部 <code>field</code> 字段.</p>
<h3 id="res-type">res.type</h3>
<p> 获取响应 <code>Content-Type</code> 字段, 不包含参数如 "charset".</p>
<pre><code class="lang-js">var ct = this.type;
// => "image/png"</code></pre>
<h3 id="res-type-">res.type=</h3>
<p> 通过 mime 字符串或文件扩展名设置响应 <code>Content-Type</code>.</p>
<pre><code class="lang-js">this.type = 'text/plain; charset=utf-8';
this.type = 'image/png';
this.type = '.png';
this.type = 'png';</code></pre>
<p> 注意: 当合适的 <code>charset</code> 可以确定, 会自动设置, 例如 <code>res.type = 'html'</code>
会自动设置为 "utf-8", 但是如果设置完整时, charset 不会自动设定,
如 <code>res.type = 'text/html'</code>.</p>
<h3 id="res-is-types-">res.is(types...)</h3>
<p> 跟 <code>this.request.is()</code> 非常相似.
检查响应 type 是否是提供的 types 之一.
该方法在开发修改响应内容的中间件时非常有用</p>
<p> 例如这是一个压缩 html 响应的中间件, 他不会处理 streams 类型.</p>
<pre><code class="lang-js">var minify = require('html-minifier');
app.use(function *minifyHTML(next){
yield next;
if (!this.response.is('html')) return;
var body = this.body;
if (!body || body.pipe) return;
if (Buffer.isBuffer(body)) body = body.toString();
this.body = minify(body);
});</code></pre>
<h3 id="res-redirect-url-alt-">res.redirect(url, [alt])</h3>
<p> 执行 [302] 重定向到 <code>url</code>.</p>
<p> 字符 "back" 是一种特殊用法, 能提供 Referrer支持, 当没有 Referrer时 使用<code>alt</code> 或 "/"</p>
<pre><code class="lang-js">this.redirect('back');
this.redirect('back', '/index.html');
this.redirect('/login');
this.redirect('http://google.com');</code></pre>
<p> 如果想要修改默认状态 <code>302</code>, 直接在重定向之前或之后设定 status, 如果想修改 body , 需要
在重定向之后执行. </p>
<pre><code class="lang-js">this.status = 301;
this.redirect('/cart');
this.body = 'Redirecting to shopping cart';</code></pre>
<h3 id="res-attachment-filename-">res.attachment([filename])</h3>
<p> 设置 "attachment" 的 <code>Content-Disposition</code> 用于给客户端发送信号, 提示下载.
下载文件的名字可以通过参数设置.</p>
<h3 id="res-headersent">res.headerSent</h3>
<p> 检查响应头是否已经发送. 在有错误时检查 client 是否被通知时有用.</p>
<h3 id="res-lastmodified">res.lastModified</h3>
<p> 如果响应头部包含 <code>Last-Modified</code>, 返回 <code>Date</code>.</p>
<h3 id="res-lastmodified-">res.lastModified=</h3>
<p> 将 <code>Last-Modified</code> 头部设置为正确的 UTC string. 可以使用 <code>Date</code> 或 date 字符串设置.</p>
<pre><code class="lang-js">this.response.lastModified = new Date();</code></pre>
<h3 id="res-etag-">res.etag=</h3>
<p> 设置响应的 ETag (包括 wrapped <code>"</code>). 注意没有对应的 <code>res.etag</code> 获取器.</p>
<pre><code class="lang-js">this.response.etag = crypto.createHash('md5').update(this.body).digest('hex');</code></pre>
<h3 id="res-vary-field-">res.vary(field)</h3>
<p> Vary on <code>field</code>.</p>
</div></section><section><div class="content"><h1 id="guide">Guide</h1>
<p> 这节内容跟 API 无关, 而是中间件开发最佳实践, 应用架构建议等.</p>
<h2 id="-">开发中间件</h2>
<p> Koa 中间件是返回 <code>GeneratorFunction</code> 的方法, 并接受其他的中间件. 当某个中间件被 "upstream" 中间件执行时, 它必须手动 <code>yield</code>
"downstream" 中间件</p>
<p> 例如你想记录 request 传递经过 Koa 的时间, 可以开发一个添加 <code>X-Response-Time</code> 头字段的中间件.</p>
<pre><code class="lang-js">function *responseTime(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
}
app.use(responseTime);</code></pre>
<p> 如下是一个等价的 inline 中间件:</p>
<pre><code class="lang-js">app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});</code></pre>
<p> 如果你是一个前端工程师, 可以把所有 <code>yield next;</code> 之前的代码看做 "capture" 阶段, 把之后的代码看做 "bubble" 阶段.
如下 gif 展示了 ES6 generators 如何让我们合理的使用 stack flow 实现 request and response flows:</p>
<p><img src="https://github.com/koajs/koa/raw/master/docs/middleware.gif" alt="koa middleware"></p>
<ol>
<li>创建 date 记录花费时间</li>
<li>将控制 Yield 到下一个 middleware</li>
<li>创建另外 date 记录响应时间</li>
<li>将控制 Yield 到下一个 middleware</li>
<li>立刻 Yield 控制, 因为 <code>contentLength</code> 只对 response 起作用</li>
<li>将 upstream Yield 到 Koa 的 空middleware.</li>
<li>如果请求路径不是 "/", 则跳过设置 body.</li>
<li>设置响应为 "Hello World"</li>
<li>如果有 body 则设置 <code>Content-Length</code></li>
<li>设置头部字段</li>
<li>输出log</li>
<li>发送响应前设置 <code>X-Response-Time</code> 头字段</li>
<li>转会 Koa, Koa负责发送 response</li>
</ol>
<p>注意最后的中间件 (step <strong>6</strong>) yields, 看起来没有转给任何东西, 但实际上他转给了 Koa 的空 generator. 这是为了保证所有
的中间件遵循相同的 API, 可以在其他中间件前边或后边使用. 如果你删掉最深 "downstream" 中间件的 <code>yield next;</code> 所有的功能
都还 OK, 但是不在遵循这个行为.</p>
<p> 例如如下代码也不会出错:</p>
<pre><code class="lang-js">app.use(function *response(){
if ('/' != this.url) return;
this.body = 'Hello World';
});</code></pre>
<p>接下来是中间件开发最佳实践</p>
<h2 id="-">中间件最佳实践</h2>
<p> 这个环节介绍了中间件开发最佳实践相关内容: 可接受的选项, 给中间件命名有利于调试, 及其他.</p>
<h3 id="-">中间件选项</h3>
<p> 在开发中间件时遵循惯例是非常重要的: 使用接受参数的方法 wrapping 中间件, 这样用户可以扩展功能.
即使你的中间件不接受选项, 保持所有事情一致也是最好的选择.</p>
<p> 如下是一个 <code>logger</code> 中间件, 接受 <code>format</code> 字符串, 用于自定义格式, 最后返回中间件.</p>
<pre><code class="lang-js">function logger(format){
format = format || ':method ":url"';
return function *(next){
var str = format
.replace(':method', this.method)
.replace(':url', this.url);
console.log(str);
yield next;
}
}
app.use(logger());
app.use(logger(':method :url'));</code></pre>
<h3 id="-">给中间件命名</h3>
<p> 中间件命名不是强制的, 但如果中间件有名字, 在调试时会非常有帮助.</p>
<pre><code class="lang-js">function logger(format){
return function *logger(next){
}
}</code></pre>
<h3 id="-">将多个中间件组合为一个</h3>
<p> 有时候你需要将多个中间件组合成一个, 从而方便重用或 exporting. 这时你可以用 <code>.call(this, next)</code> 将他们连起来, 然后将 yield 这个 chain 的方法返回.</p>
<pre><code class="lang-js">function *random(next){
if ('/random' == this.path) {
this.body = Math.floor(Math.random()*10);
} else {
yield next;
}
};
function *backwords(next) {
if ('/backwords' == this.path) {
this.body = 'sdrowkcab';
} else {
yield next;
}
}
function *pi(next){
if ('/pi' == this.path) {
this.body = String(Math.PI);
} else {
yield next;
}
}
function *all(next) {
yield random.call(this, backwords.call(this, pi.call(this, next)));
}
app.use(all);</code></pre>
<p> Koa 内部 使用 koa-compose 创建和调度中间件栈. <a href="https://github.com/koajs/compose">koa-compose</a> 内部就是这样实现的.</p>
<h3 id="-">响应中间件</h3>
<p> 如果中间件用于响应请求, 需要跳过 downstream 的中间件可以直接省略 <code>yield next</code>. 通常路由中间件就是这样的, 而且在所有中间件里都可以省略.
例如下面的例子会响应 "two", 但是三个都被执行了, 所以在 downstream "three" 中间件里就有可能修改响应结果.</p>
<pre><code class="lang-js">app.use(function *(next){
console.log('>> one');
yield next;
console.log('<< one');
});
app.use(function *(next){
console.log('>> two');
this.body = 'two';
yield next;
console.log('<< two');
});
app.use(function *(next){
console.log('>> three');
yield next;
console.log('<< three');
});</code></pre>
<p> The following configuration omits <code>yield next</code> in the second middleware, and will still respond
with "two", however the third (and any other downstream middleware) will be ignored:
在下面的例子中第二个中间件省略了 <code>yield next</code>, 最终响应结果还是 "two", 但是第三个(以后后面所有的 downstream 中间件)中间件被忽略了.</p>
<pre><code class="lang-js">app.use(function *(next){
console.log('>> one');
yield next;
console.log('<< one');
});
app.use(function *(next){
console.log('>> two');
this.body = 'two';
console.log('<< two');
});
app.use(function *(next){
console.log('>> three');
yield next;
console.log('<< three');
});</code></pre>
<p> 当最深的中间件执行 <code>yield next;</code>, 它实际上是 yield 的空方法, 这样可以保证 stack 中所有地方的中间件可以正常 compose.</p>
<h2 id="-">异步操作</h2>
<p> <a href="https://github.com/visionmedia/co">Co</a> 构成了 Koa generator 委托的基石. 让我们可以写非阻塞的顺序代码.
例如如下代码. 读取 <code>./docs</code> 中的所有文件名, 并读取所有 markdown 的内容, 连接后赋给 body, 这所有的异步操作都是使用
顺序代码实现的.</p>
<pre><code class="lang-js">var fs = require('co-fs');
app.use(function *(){
var paths = yield fs.readdir('docs');
var files = yield paths.map(function(path){
return fs.readFile('docs/' + path, 'utf8');
});
this.type = 'markdown';
this.body = files.join('');
});</code></pre>
<h2 id="-koa">调试 Koa</h2>
<p>Koa 和许多相关的库都支持 <strong>DEBUG</strong> 环境变量. 这是通过 <a href="https://github.com/visionmedia/debug">debug</a> 实现的, debug 提供简单的条件 logging.</p>
<p> 例如, 如果想查看所有 koa 调试信息, 设置环境变量为 <code>DEBUG=koa*</code>, 这样在程序启动的时候, 可以看到所有使用的中间件列表.</p>
<pre><code>$ DEBUG=koa* node --harmony examples/simple
koa:application use responseTime +0ms
koa:application use logger +4ms
koa:application use contentLength +0ms
koa:application use notfound +0ms
koa:application use response +0ms
koa:application listen +0ms</code></pre>
<p> 虽然 JavaScript 不允许动态定义方法名, 但是你可以将中间件的名字设置为 <code>._name</code>.
这在你无法修改中间件名字时非常有用如:</p>
<pre><code class="lang-js">var path = require('path');
var static = require('koa-static');
var publicFiles = static(path.join(__dirname, 'public'));
publicFiles._name = 'static /public';
app.use(publicFiles);</code></pre>
<p> 现在, 在调试模式你不仅可以看到 "static", 还能:</p>
<pre><code> koa:application use static /public +0ms</code></pre>
</div></section><section><div class="content"><h1 id="links">相关链接</h1><p>相关社区, 可以发现Koa第三方中间件, 完整可运行例子, 简明的指导,以及更多.
如果发现问题可以在IRC上提出讨论.
</p><ul><li><a href="https://github.com/koajs">GitHub organization</a></li><li><a href="https://github.com/koajs/koa">GitHub repository</a></li><li><a href="https://github.com/koajs/examples">Examples</a></li><li><a href="https://github.com/koajs/koa/wiki">Middleware</a></li><li><a href="https://github.com/koajs/koa/wiki">Wiki</a></li><li><a href="https://plus.google.com/communities/101845768320796750641">G+ Community</a></li><li><a href="https://groups.google.com/forum/#!forum/koajs">Mailing list</a></li><li><a href="https://github.com/koajs/koa/blob/master/docs/guide.md">Guide</a></li><li><a href="https://github.com/koajs/koa/blob/master/docs/faq.md">FAQ</a></li><li><a href="http://koajs.com/">Koajs.com</a></li><li><a href="https://sourcegraph.com/koajs">sourcegraph koajs</a></li><li><a href="https://npmjs.org/package/koa">NPM koa</a></li><li><a href="http://koajs.cn/">Koajs.cn</a></li><li><strong>#koajs</strong> on freenode</li></ul></div></section><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46116808-3', 'rednode.cn');
ga('send', 'pageview');</script></body></html>