-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.html
803 lines (766 loc) · 52.9 KB
/
index.html
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
<!DOCTYPE html><html><head><title>Koa - next generation web framework for node.js</title><link rel="stylesheet" href="public/style.css"><link rel="stylesheet" href="public/icons/css/slate.css"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Italiana&subset=latin"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/github.min.css"><meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0"><script>window.analytics=window.analytics||[],window.analytics.methods=["identify","group","track","page","pageview","alias","ready","on","once","off","trackLink","trackForm","trackClick","trackSubmit"],window.analytics.factory=function(t){return function(){var a=Array.prototype.slice.call(arguments);return a.unshift(t),window.analytics.push(a),window.analytics}};for(var i=0;i<window.analytics.methods.length;i++){var key=window.analytics.methods[i];window.analytics[key]=window.analytics.factory(key)}window.analytics.load=function(t){if(!document.getElementById("analytics-js")){var a=document.createElement("script");a.type="text/javascript",a.id="analytics-js",a.async=!0,a.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.io/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n)}},window.analytics.SNIPPET_VERSION="2.0.9",
window.analytics.load("9u0xff0b3k");
window.analytics.page();</script><script src="stats.js"></script><script src="https://embed.runkit.com" async defer></script></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="#links">Links</a></li></ul></div><div id="heading"><div id="logo">Koa</div><div id="tagline">next generation web framework for node.js</div></div></section><section><div class="content"><h1 id="introduction">Introduction</h1><p>Koa is a new web framework designed by the team behind Express,
which aims to be a smaller, more expressive, and more robust foundation
for web applications and APIs. By leveraging async functions, Koa allows you
to ditch callbacks and greatly increase error-handling. Koa does not bundle any
middleware within its core, and it provides an elegant suite of methods that make
writing servers fast and enjoyable.
</p></div></section><section><div class="content"><h1 id="installation">Installation</h1>
<p> Koa requires <strong>node v12</strong> or higher for ES2015 and async function support.</p>
<p> You can quickly install a supported version of node with your favorite version manager:</p>
<div id = "example-0"><pre><code class = "lang-bash">$ nvm install 7
$ npm i koa
$ node my-koa-app.js</code></pre></div><h1 id="application">Application</h1>
<p> A Koa application is an object containing an array of middleware functions
which are composed and executed in a stack-like manner upon request. Koa is similar to many
other middleware systems that you may have encountered such as Ruby's Rack, Connect, and so on -
however a key design decision was made to provide high level "sugar" at the otherwise low-level
middleware layer. This improves interoperability, robustness, and makes writing middleware much
more enjoyable.</p>
<p> This includes methods for common tasks like content-negotiation, cache freshness, proxy support, and redirection
among others. Despite supplying a reasonably large number of helpful methods Koa maintains a small footprint, as
no middleware are bundled.</p>
<p> The obligatory hello world application:</p>
<!-- runkit:endpoint -->
<div id = "example-1"><pre><code class = "lang-js">const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);</code></pre></div><script>(function endpoint(id, count) {
if (!window.RunKit)
if (typeof count === "undefined" || count < 20)
return setTimeout(endpoint, 500, id, count || 0 + 1);
else
return;
var parent = document.getElementById(id);
var source = parent.textContent;
parent.innerHTML = "";
RunKit.createNotebook({
element: parent,
nodeVersion: "8.x.x",
source: source,
mode: "endpoint"
});
})("example-1")</script><h2 id="cascading">Cascading</h2>
<p> Koa middleware cascade in a more traditional way as you may be used to with similar tools -
this was previously difficult to make user friendly with node's use of callbacks.
However with async functions we can achieve "true" middleware. Contrasting Connect's implementation which
simply passes control through series of functions until one returns, Koa invoke "downstream", then
control flows back "upstream".</p>
<p> The following example responds with "Hello World", however first the request flows through
the <code>x-response-time</code> and <code>logging</code> middleware to mark when the request started, then yields control through the response middleware. When a middleware invokes <code>next()</code>
the function suspends and passes control to the next middleware defined. After there are no more
middleware to execute downstream, the stack will unwind and each middleware is resumed to perform
its upstream behaviour.</p>
<!-- runkit:endpoint -->
<div id = "example-2"><pre><code class = "lang-js">const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);</code></pre></div><script>(function endpoint(id, count) {
if (!window.RunKit)
if (typeof count === "undefined" || count < 20)
return setTimeout(endpoint, 500, id, count || 0 + 1);
else
return;
var parent = document.getElementById(id);
var source = parent.textContent;
parent.innerHTML = "";
RunKit.createNotebook({
element: parent,
nodeVersion: "8.x.x",
source: source,
mode: "endpoint"
});
})("example-2")</script><h2 id="settings">Settings</h2>
<p> Application settings are properties on the <code>app</code> instance, currently
the following are supported:</p>
<ul>
<li><code>app.env</code> defaulting to the <strong>NODE_ENV</strong> or "development"</li>
<li><code>app.keys</code> array of signed cookie keys</li>
<li><code>app.proxy</code> when true proxy header fields will be trusted</li>
<li><code>app.subdomainOffset</code> offset of <code>.subdomains</code> to ignore, default to 2</li>
<li><code>app.proxyIpHeader</code> proxy ip header, default to <code>X-Forwarded-For</code></li>
<li><p><code>app.maxIpsCount</code> max ips read from proxy ip header, default to 0 (means infinity)</p>
<p>You can pass the settings to the constructor:</p>
<div id = "example-3"><pre><code class = "lang-js">const Koa = require('koa');
const app = new Koa({ proxy: true });</code></pre></div><p>or dynamically:</p>
<div id = "example-4"><pre><code class = "lang-js">const Koa = require('koa');
const app = new Koa();
app.proxy = true;</code></pre></div></li>
</ul>
<h2 id="app-listen-">app.listen(...)</h2>
<p> A Koa application is not a 1-to-1 representation of an HTTP server.
One or more Koa applications may be mounted together to form larger
applications with a single HTTP server.</p>
<p> Create and return an HTTP server, passing the given arguments to
<code>Server#listen()</code>. These arguments are documented on <a href="http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback">nodejs.org</a>. The following is a useless Koa application bound to port <code>3000</code>:</p>
<div id = "example-5"><pre><code class = "lang-js">const Koa = require('koa');
const app = new Koa();
app.listen(3000);</code></pre></div><p> The <code>app.listen(...)</code> method is simply sugar for the following:</p>
<div id = "example-6"><pre><code class = "lang-js">const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);</code></pre></div><p> This means you can spin up the same application as both HTTP and HTTPS
or on multiple addresses:</p>
<div id = "example-7"><pre><code class = "lang-js">const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);</code></pre></div><h2 id="app-callback-">app.callback()</h2>
<p> Return a callback function suitable for the <code>http.createServer()</code>
method to handle a request.
You may also use this callback function to mount your Koa app in a
Connect/Express app.</p>
<h2 id="app-use-function-">app.use(function)</h2>
<p> Add the given middleware function to this application.
<code>app.use()</code> returns <code>this</code>, so is chainable.</p>
<div id = "example-8"><pre><code class = "lang-js">app.use(someMiddleware)
app.use(someOtherMiddleware)
app.listen(3000)</code></pre></div><p> Is the same as</p>
<div id = "example-9"><pre><code class = "lang-js">app.use(someMiddleware)
.use(someOtherMiddleware)
.listen(3000)</code></pre></div><p> See <a href="https://github.com/koajs/koa/wiki#middleware">Middleware</a> for
more information.</p>
<h2 id="app-keys-">app.keys=</h2>
<p> Set signed cookie keys.</p>
<p> These are passed to <a href="https://github.com/crypto-utils/keygrip">KeyGrip</a>,
however you may also pass your own <code>KeyGrip</code> instance. For
example the following are acceptable:</p>
<div id = "example-10"><pre><code class = "lang-js">app.keys = ['OEK5zjaAMPc3L6iK7PyUjCOziUH3rsrMKB9u8H07La1SkfwtuBoDnHaaPCkG5Brg', 'MNKeIebviQnCPo38ufHcSfw3FFv8EtnAe1xE02xkN1wkCV1B2z126U44yk2BQVK7'];
app.keys = new KeyGrip(['OEK5zjaAMPc3L6iK7PyUjCOziUH3rsrMKB9u8H07La1SkfwtuBoDnHaaPCkG5Brg', 'MNKeIebviQnCPo38ufHcSfw3FFv8EtnAe1xE02xkN1wkCV1B2z126U44yk2BQVK7'], 'sha256');</code></pre></div><p> For security reasons, please ensure that the key is long enough and random.</p>
<p> These keys may be rotated and are used when signing cookies
with the <code>{ signed: true }</code> option:</p>
<div id = "example-11"><pre><code class = "lang-js">ctx.cookies.set('name', 'tobi', { signed: true });</code></pre></div><h2 id="app-context">app.context</h2>
<p> <code>app.context</code> is the prototype from which <code>ctx</code> is created.
You may add additional properties to <code>ctx</code> by editing <code>app.context</code>.
This is useful for adding properties or methods to <code>ctx</code> to be used across your entire app,
which may be more performant (no middleware) and/or easier (fewer <code>require()</code>s)
at the expense of relying more on <code>ctx</code>, which could be considered an anti-pattern.</p>
<p> For example, to add a reference to your database from <code>ctx</code>:</p>
<div id = "example-12"><pre><code class = "lang-js">app.context.db = db();
app.use(async ctx => {
console.log(ctx.db);
});</code></pre></div><p>Note:</p>
<ul>
<li>Many properties on <code>ctx</code> are defined using getters, setters, and <code>Object.defineProperty()</code>. You can only edit these properties (not recommended) by using <code>Object.defineProperty()</code> on <code>app.context</code>. See <a href="https://github.com/koajs/koa/issues/652">https://github.com/koajs/koa/issues/652</a>.</li>
<li>Mounted apps currently use their parent's <code>ctx</code> and settings. Thus, mounted apps are really just groups of middleware.</li>
</ul>
<h2 id="error-handling">Error Handling</h2>
<p> By default outputs all errors to stderr unless <code>app.silent</code> is <code>true</code>.
The default error handler also won't output errors when <code>err.status</code> is <code>404</code> or <code>err.expose</code> is <code>true</code>.
To perform custom error-handling logic such as centralized logging you can add an "error" event listener:</p>
<div id = "example-13"><pre><code class = "lang-js">app.on('error', err => {
log.error('server error', err)
});</code></pre></div><p> If an error is in the req/res cycle and it is <em>not</em> possible to respond to the client, the <code>Context</code> instance is also passed:</p>
<div id = "example-14"><pre><code class = "lang-js">app.on('error', (err, ctx) => {
log.error('server error', err, ctx)
});</code></pre></div><p> When an error occurs <em>and</em> it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond
appropriately with a 500 "Internal Server Error". In either case
an app-level "error" is emitted for logging purposes.</p>
</div></section><section><div class="content"><h1 id="context">Context</h1>
<p> A Koa Context encapsulates node's <code>request</code> and <code>response</code> objects
into a single object which provides many helpful methods for writing
web applications and APIs.
These operations are used so frequently in HTTP server development
that they are added at this level instead of a higher level framework,
which would force middleware to re-implement this common functionality.</p>
<p> A <code>Context</code> is created <em>per</em> request, and is referenced in middleware
as the receiver, or the <code>ctx</code> identifier, as shown in the following
snippet:</p>
<div id = "example-15"><pre><code class = "lang-js">app.use(async ctx => {
ctx; // is the Context
ctx.request; // is a Koa Request
ctx.response; // is a Koa Response
});</code></pre></div><p> Many of the context's accessors and methods simply delegate to their <code>ctx.request</code> or <code>ctx.response</code>
equivalents for convenience, and are otherwise identical. For example <code>ctx.type</code> and <code>ctx.length</code>
delegate to the <code>response</code> object, and <code>ctx.path</code> and <code>ctx.method</code> delegate to the <code>request</code>.</p>
<h2 id="api">API</h2>
<p> <code>Context</code> specific methods and accessors.</p>
<h3 id="ctx-req">ctx.req</h3>
<p> Node's <code>request</code> object.</p>
<h3 id="ctx-res">ctx.res</h3>
<p> Node's <code>response</code> object.</p>
<p> Bypassing Koa's response handling is <strong>not supported</strong>. Avoid using the following node properties:</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> A Koa <code>Request</code> object.</p>
<h3 id="ctx-response">ctx.response</h3>
<p> A Koa <code>Response</code> object.</p>
<h3 id="ctx-state">ctx.state</h3>
<p> The recommended namespace for passing information through middleware and to your frontend views.</p>
<div id = "example-16"><pre><code class = "lang-js">ctx.state.user = await User.find(id);</code></pre></div><h3 id="ctx-app">ctx.app</h3>
<p> Application instance reference.</p>
<h3 id="ctx-app-emit">ctx.app.emit</h3>
<p> Koa applications extend an internal <a href="https://nodejs.org/dist/latest-v11.x/docs/api/events.html">EventEmitter</a>. <code>ctx.app.emit</code> emits an event with a type, defined by the first argument. For each event you can hook up "listeners", which is a function that is called when the event is emitted. Consult the <a href="https://koajs.com/#error-handling">error handling docs</a> for more information.</p>
<h3 id="ctx-cookies-get-name-options-">ctx.cookies.get(name, [options])</h3>
<p> Get cookie <code>name</code> with <code>options</code>:</p>
<ul>
<li><code>signed</code> the cookie requested should be signed</li>
</ul>
<p>Koa uses the <a href="https://github.com/pillarjs/cookies">cookies</a> module where options are simply passed.</p>
<h3 id="ctx-cookies-set-name-value-options-">ctx.cookies.set(name, value, [options])</h3>
<p> Set cookie <code>name</code> to <code>value</code> with <code>options</code>:</p>
<ul>
<li><code>maxAge</code>: a number representing the milliseconds from <code>Date.now()</code> for expiry.</li>
<li><code>expires</code>: a <code>Date</code> object indicating the cookie's expiration date (expires at the end of session by default).</li>
<li><code>path</code>: a string indicating the path of the cookie (<code>/</code> by default).</li>
<li><code>domain</code>: a string indicating the domain of the cookie (no default).</li>
<li><code>secure</code>: a boolean indicating whether the cookie is only to be sent over HTTPS (<code>false</code> by default for HTTP, <code>true</code> by default for HTTPS). <a href="https://github.com/pillarjs/cookies#secure-cookies">Read more about this option</a>.</li>
<li><code>httpOnly</code>: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (<code>true</code> by default).</li>
<li><code>sameSite</code>: a boolean or string indicating whether the cookie is a "same site" cookie (<code>false</code> by default). This can be set to <code>'strict'</code>, <code>'lax'</code>, <code>'none'</code>, or <code>true</code> (which maps to <code>'strict'</code>).</li>
<li><code>signed</code>: a boolean indicating whether the cookie is to be signed (<code>false</code> by default). If this is true, another cookie of the same name with the <code>.sig</code> suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of <em>cookie-name</em>=<em>cookie-value</em> against the first <a href="https://www.npmjs.com/package/keygrip">Keygrip</a> key. This signature key is used to detect tampering the next time a cookie is received.</li>
<li><code>overwrite</code>: a boolean indicating whether to overwrite previously set cookies of the same name (<code>false</code> by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.</li>
</ul>
<p>Koa uses the <a href="https://github.com/pillarjs/cookies">cookies</a> module where options are simply passed.</p>
<h3 id="ctx-throw-status-msg-properties-">ctx.throw([status], [msg], [properties])</h3>
<p> Helper method to throw an error with a <code>.status</code> property
defaulting to <code>500</code> that will allow Koa to respond appropriately.
The following combinations are allowed:</p>
<div id = "example-17"><pre><code class = "lang-js">ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });</code></pre></div><p> For example <code>ctx.throw(400, 'name required')</code> is equivalent to:</p>
<div id = "example-18"><pre><code class = "lang-js">const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;</code></pre></div><p> Note that these are user-level errors and are flagged with
<code>err.expose</code> meaning the messages are appropriate for
client responses, which is typically not the case for
error messages since you do not want to leak failure
details.</p>
<p> You may optionally pass a <code>properties</code> object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.</p>
<div id = "example-19"><pre><code class = "lang-js">ctx.throw(401, 'access_denied', { user: user });</code></pre></div><p>Koa uses <a href="https://github.com/jshttp/http-errors">http-errors</a> to create errors. <code>status</code> should only be passed as the first parameter.</p>
<h3 id="ctx-assert-value-status-msg-properties-">ctx.assert(value, [status], [msg], [properties])</h3>
<p> Helper method to throw an error similar to <code>.throw()</code>
when <code>!value</code>. Similar to node's <a href="http://nodejs.org/api/assert.html">assert()</a>
method.</p>
<div id = "example-20"><pre><code class = "lang-js">ctx.assert(ctx.state.user, 401, 'User not found. Please login!');</code></pre></div><p>Koa uses <a href="https://github.com/jshttp/http-assert">http-assert</a> for assertions.</p>
<h3 id="ctx-respond">ctx.respond</h3>
<p> To bypass Koa's built-in response handling, you may explicitly set <code>ctx.respond = false;</code>. Use this if you want to write to the raw <code>res</code> object instead of letting Koa handle the response for you.</p>
<p> Note that using this is <strong>not</strong> supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional <code>fn(req, res)</code> functions and middleware within Koa.</p>
<h2 id="request-aliases">Request aliases</h2>
<p> The following accessors and alias <a href="#request">Request</a> equivalents:</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.origin</code></li>
<li><code>ctx.href</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-aliases">Response aliases</h2>
<p> The following accessors and alias <a href="#response">Response</a> equivalents:</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.message</code></li>
<li><code>ctx.message=</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.append()</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> A Koa <code>Request</code> object is an abstraction on top of node's vanilla request object,
providing additional functionality that is useful for every day HTTP server
development.</p>
<h2 id="api">API</h2>
<h3 id="request-header">request.header</h3>
<p> Request header object. This is the same as the <a href="https://nodejs.org/api/http.html#http_message_headers"><code>headers</code></a> field
on node's <a href="https://nodejs.org/api/http.html#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p>
<h3 id="request-header-">request.header=</h3>
<p> Set request header object.</p>
<h3 id="request-headers">request.headers</h3>
<p> Request header object. Alias as <code>request.header</code>.</p>
<h3 id="request-headers-">request.headers=</h3>
<p> Set request header object. Alias as <code>request.header=</code>.</p>
<h3 id="request-method">request.method</h3>
<p> Request method.</p>
<h3 id="request-method-">request.method=</h3>
<p> Set request method, useful for implementing middleware
such as <code>methodOverride()</code>.</p>
<h3 id="request-length">request.length</h3>
<p> Return request Content-Length as a number when present, or <code>undefined</code>.</p>
<h3 id="request-url">request.url</h3>
<p> Get request URL.</p>
<h3 id="request-url-">request.url=</h3>
<p> Set request URL, useful for url rewrites.</p>
<h3 id="request-originalurl">request.originalUrl</h3>
<p> Get request original URL.</p>
<h3 id="request-origin">request.origin</h3>
<p> Get origin of URL, include <code>protocol</code> and <code>host</code>.</p>
<div id = "example-21"><pre><code class = "lang-js">ctx.request.origin
// => http://example.com</code></pre></div><h3 id="request-href">request.href</h3>
<p> Get full request URL, include <code>protocol</code>, <code>host</code> and <code>url</code>.</p>
<div id = "example-22"><pre><code class = "lang-js">ctx.request.href;
// => http://example.com/foo/bar?q=1</code></pre></div><h3 id="request-path">request.path</h3>
<p> Get request pathname.</p>
<h3 id="request-path-">request.path=</h3>
<p> Set request pathname and retain query-string when present.</p>
<h3 id="request-querystring">request.querystring</h3>
<p> Get raw query string void of <code>?</code>.</p>
<h3 id="request-querystring-">request.querystring=</h3>
<p> Set raw query string.</p>
<h3 id="request-search">request.search</h3>
<p> Get raw query string with the <code>?</code>.</p>
<h3 id="request-search-">request.search=</h3>
<p> Set raw query string.</p>
<h3 id="request-host">request.host</h3>
<p> Get host (hostname:port) when present. Supports <code>X-Forwarded-Host</code>
when <code>app.proxy</code> is <strong>true</strong>, otherwise <code>Host</code> is used.</p>
<h3 id="request-hostname">request.hostname</h3>
<p> Get hostname when present. Supports <code>X-Forwarded-Host</code>
when <code>app.proxy</code> is <strong>true</strong>, otherwise <code>Host</code> is used.</p>
<p> If host is IPv6, Koa delegates parsing to
<a href="https://nodejs.org/dist/latest-v8.x/docs/api/url.html#url_the_whatwg_url_api">WHATWG URL API</a>,
<em>Note</em> This may impact performance.</p>
<h3 id="request-url">request.URL</h3>
<p> Get WHATWG parsed URL object.</p>
<h3 id="request-type">request.type</h3>
<p> Get request <code>Content-Type</code> void of parameters such as "charset".</p>
<div id = "example-23"><pre><code class = "lang-js">const ct = ctx.request.type;
// => "image/png"</code></pre></div><h3 id="request-charset">request.charset</h3>
<p> Get request charset when present, or <code>undefined</code>:</p>
<div id = "example-24"><pre><code class = "lang-js">ctx.request.charset;
// => "utf-8"</code></pre></div><h3 id="request-query">request.query</h3>
<p> Get parsed query-string, returning an empty object when no
query-string is present. Note that this getter does <em>not</em>
support nested parsing.</p>
<p> For example "color=blue&size=small":</p>
<div id = "example-25"><pre><code class = "lang-js">{
color: 'blue',
size: 'small'
}</code></pre></div><h3 id="request-query-">request.query=</h3>
<p> Set query-string to the given object. Note that this
setter does <em>not</em> support nested objects.</p>
<div id = "example-26"><pre><code class = "lang-js">ctx.query = { next: '/login' };</code></pre></div><h3 id="request-fresh">request.fresh</h3>
<p> Check if a request cache is "fresh", aka the contents have not changed. This
method is for cache negotiation between <code>If-None-Match</code> / <code>ETag</code>, and <code>If-Modified-Since</code> and <code>Last-Modified</code>. It should be referenced after setting one or more of these response headers.</p>
<div id = "example-27"><pre><code class = "lang-js">// freshness check requires status 20x or 304
ctx.status = 200;
ctx.set('ETag', '123');
// cache is ok
if (ctx.fresh) {
ctx.status = 304;
return;
}
// cache is stale
// fetch new data
ctx.body = await db.find('something');</code></pre></div><h3 id="request-stale">request.stale</h3>
<p> Inverse of <code>request.fresh</code>.</p>
<h3 id="request-protocol">request.protocol</h3>
<p> Return request protocol, "https" or "http". Supports <code>X-Forwarded-Proto</code>
when <code>app.proxy</code> is <strong>true</strong>.</p>
<h3 id="request-secure">request.secure</h3>
<p> Shorthand for <code>ctx.protocol == "https"</code> to check if a request was
issued via TLS.</p>
<h3 id="request-ip">request.ip</h3>
<p> Request remote address. Supports <code>X-Forwarded-For</code> when <code>app.proxy</code>
is <strong>true</strong>.</p>
<h3 id="request-ips">request.ips</h3>
<p> When <code>X-Forwarded-For</code> is present and <code>app.proxy</code> is enabled an array
of these ips is returned, ordered from upstream -> downstream. When
disabled an empty array is returned.</p>
<p> For example if the value were "client, proxy1, proxy2",
you would receive the array <code>["client", "proxy1", "proxy2"]</code>.</p>
<p> Most of the reverse proxy(nginx) set x-forwarded-for via
<code>proxy_add_x_forwarded_for</code>, which poses a certain security risk.
A malicious attacker can forge a client's ip address by forging
a <code>X-Forwarded-For</code>request header. The request sent by the client
has an <code>X-Forwarded-For</code> request header for 'forged'. After being
forwarded by the reverse proxy, <code>request.ips</code> will be
['forged', 'client', 'proxy1', 'proxy2'].</p>
<p> Koa offers two options to avoid being bypassed.</p>
<p> If you can control the reverse proxy, you can avoid bypassing
by adjusting the configuration, or use the <code>app.proxyIpHeader</code>
provided by koa to avoid reading <code>x-forwarded-for</code> to get ips.</p>
<div id = "example-28"><pre><code class = "lang-js"> const app = new Koa({
proxy: true,
proxyIpHeader: 'X-Real-IP',
});</code></pre></div><p> If you know exactly how many reverse proxies are in front of
the server, you can avoid reading the user's forged request
header by configuring <code>app.maxIpsCount</code>:</p>
<div id = "example-29"><pre><code class = "lang-js"> const app = new Koa({
proxy: true,
maxIpsCount: 1, // only one proxy in front of the server
});
// request.header['X-Forwarded-For'] === [ '127.0.0.1', '127.0.0.2' ];
// ctx.ips === [ '127.0.0.2' ];</code></pre></div><h3 id="request-subdomains">request.subdomains</h3>
<p> Return subdomains as an array.</p>
<p> Subdomains are the dot-separated parts of the host before the main domain of
the app. By default, the domain of the app is assumed to be the last two
parts of the host. This can be changed by setting <code>app.subdomainOffset</code>.</p>
<p> For example, if the domain is "tobi.ferrets.example.com":
If <code>app.subdomainOffset</code> is not set, <code>ctx.subdomains</code> is <code>["ferrets", "tobi"]</code>.
If <code>app.subdomainOffset</code> is 3, <code>ctx.subdomains</code> is <code>["tobi"]</code>.</p>
<h3 id="request-is-types-">request.is(types...)</h3>
<p> Check if the incoming request contains the "Content-Type"
header field, and it contains any of the give mime <code>type</code>s.
If there is no request body, <code>null</code> is returned.
If there is no content type, or the match fails <code>false</code> is returned.
Otherwise, it returns the matching content-type.</p>
<div id = "example-30"><pre><code class = "lang-js">// With Content-Type: text/html; charset=utf-8
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
ctx.is('json', 'urlencoded'); // => 'json'
ctx.is('application/json'); // => 'application/json'
ctx.is('html', 'application/*'); // => 'application/json'
ctx.is('html'); // => false</code></pre></div><p> For example if you want to ensure that
only images are sent to a given route:</p>
<div id = "example-31"><pre><code class = "lang-js">if (ctx.is('image/*')) {
// process
} else {
ctx.throw(415, 'images only!');
}</code></pre></div><h3 id="content-negotiation">Content Negotiation</h3>
<p> Koa's <code>request</code> object includes helpful content negotiation utilities powered by <a href="http://github.com/expressjs/accepts">accepts</a> and <a href="https://github.com/federomero/negotiator">negotiator</a>. These utilities are:</p>
<ul>
<li><code>request.accepts(types)</code></li>
<li><code>request.acceptsEncodings(types)</code></li>
<li><code>request.acceptsCharsets(charsets)</code></li>
<li><code>request.acceptsLanguages(langs)</code></li>
</ul>
<p>If no types are supplied, <strong>all</strong> acceptable types are returned.</p>
<p>If multiple types are supplied, the best match will be returned. If no matches are found, a <code>false</code> is returned, and you should send a <code>406 "Not Acceptable"</code> response to the client.</p>
<p>In the case of missing accept headers where any type is acceptable, the first type will be returned. Thus, the order of types you supply is important.</p>
<h3 id="request-accepts-types-">request.accepts(types)</h3>
<p> Check if the given <code>type(s)</code> is acceptable, returning the best match when true, otherwise <code>false</code>. The <code>type</code> value may be one or more mime type string
such as "application/json", the extension name
such as "json", or an array <code>["json", "html", "text/plain"]</code>.</p>
<div id = "example-32"><pre><code class = "lang-js">// Accept: text/html
ctx.accepts('html');
// => "html"
// Accept: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
ctx.accepts('image/png');
ctx.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
ctx.accepts(['html', 'json']);
ctx.accepts('html', 'json');
// => "json"
// No Accept header
ctx.accepts('html', 'json');
// => "html"
ctx.accepts('json', 'html');
// => "json"</code></pre></div><p> You may call <code>ctx.accepts()</code> as many times as you like,
or use a switch:</p>
<div id = "example-33"><pre><code class = "lang-js">switch (ctx.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: ctx.throw(406, 'json, html, or text only');
}</code></pre></div><h3 id="request-acceptsencodings-encodings-">request.acceptsEncodings(encodings)</h3>
<p> Check if <code>encodings</code> are acceptable, returning the best match when true, otherwise <code>false</code>. Note that you should include <code>identity</code> as one of the encodings!</p>
<div id = "example-34"><pre><code class = "lang-js">// Accept-Encoding: gzip
ctx.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"
ctx.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"</code></pre></div><p> When no arguments are given all accepted encodings
are returned as an array:</p>
<div id = "example-35"><pre><code class = "lang-js">// Accept-Encoding: gzip, deflate
ctx.acceptsEncodings();
// => ["gzip", "deflate", "identity"]</code></pre></div><p> Note that the <code>identity</code> encoding (which means no encoding) could be unacceptable if the client explicitly sends <code>identity;q=0</code>. Although this is an edge case, you should still handle the case where this method returns <code>false</code>.</p>
<h3 id="request-acceptscharsets-charsets-">request.acceptsCharsets(charsets)</h3>
<p> Check if <code>charsets</code> are acceptable, returning
the best match when true, otherwise <code>false</code>.</p>
<div id = "example-36"><pre><code class = "lang-js">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
ctx.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"</code></pre></div><p> When no arguments are given all accepted charsets
are returned as an array:</p>
<div id = "example-37"><pre><code class = "lang-js">// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]</code></pre></div><h3 id="request-acceptslanguages-langs-">request.acceptsLanguages(langs)</h3>
<p> Check if <code>langs</code> are acceptable, returning
the best match when true, otherwise <code>false</code>.</p>
<div id = "example-38"><pre><code class = "lang-js">// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages('es', 'en');
// => "es"
ctx.acceptsLanguages(['en', 'es']);
// => "es"</code></pre></div><p> When no arguments are given all accepted languages
are returned as an array:</p>
<div id = "example-39"><pre><code class = "lang-js">// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages();
// => ["es", "pt", "en"]</code></pre></div><h3 id="request-idempotent">request.idempotent</h3>
<p> Check if the request is idempotent.</p>
<h3 id="request-socket">request.socket</h3>
<p> Return the request socket.</p>
<h3 id="request-get-field-">request.get(field)</h3>
<p> Return request header with case-insensitive <code>field</code>.</p>
</div></section><section><div class="content"><h1 id="response">Response</h1>
<p> A Koa <code>Response</code> object is an abstraction on top of node's vanilla response object,
providing additional functionality that is useful for every day HTTP server
development.</p>
<h2 id="api">API</h2>
<h3 id="response-header">response.header</h3>
<p> Response header object.</p>
<h3 id="response-headers">response.headers</h3>
<p> Response header object. Alias as <code>response.header</code>.</p>
<h3 id="response-socket">response.socket</h3>
<p> Response socket. Points to net.Socket instance as <code>request.socket</code>.</p>
<h3 id="response-status">response.status</h3>
<p> Get response status. By default, <code>response.status</code> is set to <code>404</code> unlike node's <code>res.statusCode</code> which defaults to <code>200</code>.</p>
<h3 id="response-status-">response.status=</h3>
<p> Set response status via numeric code:</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>208 "already reported"</li>
<li>226 "im used"</li>
<li>300 "multiple choices"</li>
<li>301 "moved permanently"</li>
<li>302 "found"</li>
<li>303 "see other"</li>
<li>304 "not modified"</li>
<li>305 "use proxy"</li>
<li>307 "temporary redirect"</li>
<li>308 "permanent 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 timeout"</li>
<li>409 "conflict"</li>
<li>410 "gone"</li>
<li>411 "length required"</li>
<li>412 "precondition failed"</li>
<li>413 "payload too large"</li>
<li>414 "uri too long"</li>
<li>415 "unsupported media type"</li>
<li>416 "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>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 timeout"</li>
<li>505 "http version not supported"</li>
<li>506 "variant also negotiates"</li>
<li>507 "insufficient storage"</li>
<li>508 "loop detected"</li>
<li>510 "not extended"</li>
<li>511 "network authentication required"</li>
</ul>
<p><strong>NOTE</strong>: don't worry too much about memorizing these strings,
if you have a typo an error will be thrown, displaying this list
so you can make a correction.</p>
<p> Since <code>response.status</code> default is set to <code>404</code>, to send a response
without a body and with a different status is to be done like this:</p>
<div id = "example-40"><pre><code class = "lang-js">ctx.response.status = 200;
// Or whatever other status
ctx.response.status = 204;</code></pre></div><h3 id="response-message">response.message</h3>
<p> Get response status message. By default, <code>response.message</code> is
associated with <code>response.status</code>.</p>
<h3 id="response-message-">response.message=</h3>
<p> Set response status message to the given value.</p>
<h3 id="response-length-">response.length=</h3>
<p> Set response Content-Length to the given value.</p>
<h3 id="response-length">response.length</h3>
<p> Return response Content-Length as a number when present, or deduce
from <code>ctx.body</code> when possible, or <code>undefined</code>.</p>
<h3 id="response-body">response.body</h3>
<p> Get response body.</p>
<h3 id="response-body-">response.body=</h3>
<p> Set response body to one of the following:</p>
<ul>
<li><code>string</code> written</li>
<li><code>Buffer</code> written</li>
<li><code>Stream</code> piped</li>
<li><code>Object</code> || <code>Array</code> json-stringified</li>
<li><code>null</code> || <code>undefined</code> no content response</li>
</ul>
<p>If <code>response.status</code> has not been set, Koa will automatically set the status to <code>200</code> or <code>204</code> depending on <code>response.body</code>. Specifically, if <code>response.body</code> has not been set or has been set as <code>null</code> or <code>undefined</code>, Koa will automatically set <code>response.status</code> to <code>204</code>. If you really want to send no content response with other status, you should override the <code>204</code> status as the following way:</p>
<div id = "example-41"><pre><code class = "lang-js">// This must be always set first before status, since null | undefined
// body automatically sets the status to 204
ctx.body = null;
// Now we override the 204 status with the desired one
ctx.status = 200;</code></pre></div><p>Koa doesn't guard against everything that could be put as a response body -- a function doesn't serialise meaningfully, returning a boolean may make sense based on your application, and while an error works, it may not work as intended as some properties of an error are not enumerable. We recommend adding middleware in your app that asserts body types per app. A sample middleware might be:</p>
<div id = "example-42"><pre><code class = "lang-js">app.use(async (ctx, next) => {
await next()
ctx.assert.equal('object', typeof ctx.body, 500, 'some dev did something wrong')
})</code></pre></div><h4 id="string">String</h4>
<p> The Content-Type is defaulted to text/html or text/plain, both with
a default charset of utf-8. The Content-Length field is also set.</p>
<h4 id="buffer">Buffer</h4>
<p> The Content-Type is defaulted to application/octet-stream, and Content-Length
is also set.</p>
<h4 id="stream">Stream</h4>
<p> The Content-Type is defaulted to application/octet-stream.</p>
<p> Whenever a stream is set as the response body, <code>.onerror</code> is automatically added as a listener to the <code>error</code> event to catch any errors.
In addition, whenever the request is closed (even prematurely), the stream is destroyed.
If you do not want these two features, do not set the stream as the body directly.
For example, you may not want this when setting the body as an HTTP stream in a proxy as it would destroy the underlying connection.</p>
<p> See: <a href="https://github.com/koajs/koa/pull/612">https://github.com/koajs/koa/pull/612</a> for more information.</p>
<p> Here's an example of stream error handling without automatically destroying the stream:</p>
<div id = "example-43"><pre><code class = "lang-js">const PassThrough = require('stream').PassThrough;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', (err) => ctx.onerror(err)).pipe(PassThrough());
});</code></pre></div><h4 id="object">Object</h4>
<p> The Content-Type is defaulted to application/json. This includes plain objects <code>{ foo: 'bar' }</code> and arrays <code>['foo', 'bar']</code>.</p>
<h3 id="response-get-field-">response.get(field)</h3>
<p> Get a response header field value with case-insensitive <code>field</code>.</p>
<div id = "example-44"><pre><code class = "lang-js">const etag = ctx.response.get('ETag');</code></pre></div><h3 id="response-has-field-">response.has(field)</h3>
<p> Returns <code>true</code> if the header identified by name is currently set in the outgoing headers.
The header name matching is case-insensitive.</p>
<div id = "example-45"><pre><code class = "lang-js">const rateLimited = ctx.response.has('X-RateLimit-Limit');</code></pre></div><h3 id="response-set-field-value-">response.set(field, value)</h3>
<p> Set response header <code>field</code> to <code>value</code>:</p>
<div id = "example-46"><pre><code class = "lang-js">ctx.set('Cache-Control', 'no-cache');</code></pre></div><h3 id="response-append-field-value-">response.append(field, value)</h3>
<p> Append additional header <code>field</code> with value <code>val</code>.</p>
<div id = "example-47"><pre><code class = "lang-js">ctx.append('Link', '<http://127.0.0.1/>');</code></pre></div><h3 id="response-set-fields-">response.set(fields)</h3>
<p> Set several response header <code>fields</code> with an object:</p>
<div id = "example-48"><pre><code class = "lang-js">ctx.set({
'Etag': '1234',
'Last-Modified': date
});</code></pre></div><p>This delegates to <a href="https://nodejs.org/dist/latest/docs/api/http.html#http_request_setheader_name_value">setHeader</a> which sets or updates headers by specified keys and doesn't reset the entire header.</p>
<h3 id="response-remove-field-">response.remove(field)</h3>
<p> Remove header <code>field</code>.</p>
<h3 id="response-type">response.type</h3>
<p> Get response <code>Content-Type</code> void of parameters such as "charset".</p>
<div id = "example-49"><pre><code class = "lang-js">const ct = ctx.type;
// => "image/png"</code></pre></div><h3 id="response-type-">response.type=</h3>
<p> Set response <code>Content-Type</code> via mime string or file extension.</p>
<div id = "example-50"><pre><code class = "lang-js">ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';</code></pre></div><p> Note: when appropriate a <code>charset</code> is selected for you, for
example <code>response.type = 'html'</code> will default to "utf-8". If you need to overwrite <code>charset</code>,
use <code>ctx.set('Content-Type', 'text/html')</code> to set response header field to value directly.</p>
<h3 id="response-is-types-">response.is(types...)</h3>
<p> Very similar to <code>ctx.request.is()</code>.
Check whether the response type is one of the supplied types.
This is particularly useful for creating middleware that
manipulate responses.</p>
<p> For example, this is a middleware that minifies
all HTML responses except for streams.</p>
<div id = "example-51"><pre><code class = "lang-js">const minify = require('html-minifier');
app.use(async (ctx, next) => {
await next();
if (!ctx.response.is('html')) return;
let body = ctx.body;
if (!body || body.pipe) return;
if (Buffer.isBuffer(body)) body = body.toString();
ctx.body = minify(body);
});</code></pre></div><h3 id="response-redirect-url-alt-">response.redirect(url, [alt])</h3>
<p> Perform a [302] redirect to <code>url</code>.</p>
<p> The string "back" is special-cased
to provide Referrer support, when Referrer
is not present <code>alt</code> or "/" is used.</p>
<div id = "example-52"><pre><code class = "lang-js">ctx.redirect('back');
ctx.redirect('back', '/index.html');
ctx.redirect('/login');
ctx.redirect('http://google.com');</code></pre></div><p> To alter the default status of <code>302</code>, simply assign the status
before or after this call. To alter the body, assign it after this call:</p>
<div id = "example-53"><pre><code class = "lang-js">ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';</code></pre></div><h3 id="response-attachment-filename-options-">response.attachment([filename], [options])</h3>
<p> Set <code>Content-Disposition</code> to "attachment" to signal the client
to prompt for download. Optionally specify the <code>filename</code> of the
download and some <a href="https://github.com/jshttp/content-disposition#options">options</a>.</p>
<h3 id="response-headersent">response.headerSent</h3>
<p> Check if a response header has already been sent. Useful for seeing
if the client may be notified on error.</p>
<h3 id="response-lastmodified">response.lastModified</h3>
<p> Return the <code>Last-Modified</code> header as a <code>Date</code>, if it exists.</p>
<h3 id="response-lastmodified-">response.lastModified=</h3>
<p> Set the <code>Last-Modified</code> header as an appropriate UTC string.
You can either set it as a <code>Date</code> or date string.</p>
<div id = "example-54"><pre><code class = "lang-js">ctx.response.lastModified = new Date();</code></pre></div><h3 id="response-etag-">response.etag=</h3>
<p> Set the ETag of a response including the wrapped <code>"</code>s.
Note that there is no corresponding <code>response.etag</code> getter.</p>
<div id = "example-55"><pre><code class = "lang-js">ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');</code></pre></div><h3 id="response-vary-field-">response.vary(field)</h3>
<p> Vary on <code>field</code>.</p>
<h3 id="response-flushheaders-">response.flushHeaders()</h3>
<p> Flush any set headers, and begin the body.</p>
</div></section><section><div class="content"><h1 id="sponsor">Sponsor</h1><p><a href="https://apex.sh/ping">Apex Ping </a>is a beautiful uptime monitoring solution for websites and APIs, by one of the original authors of Koa.</p><a href="https://apex.sh/ping"><img src="https://apex-inc.imgix.net/images/products/apex-ping/marketing/overview.png?auto=format&w=1400"></a></div></section><section><div class="content"><h1 id="links">Links</h1><p>Community links to discover third-party middleware for Koa, full runnable examples,
thorough guides and more! If you have questions join us in IRC!
</p><ul><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://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><strong>#koajs</strong> on freenode</li></ul></div></section></body></html>