OSDN Git Service

Regular updates
[twpd/master.git] / koa.md
1 ---
2 title: Koa
3 category: JavaScript libraries
4 layout: 2017/sheet
5 ---
6
7 ### About
8 {: .-intro}
9
10 Koa is a web framework for Node.js.
11
12 - <https://koajs.com/>
13
14 ### Reference
15
16 ```js
17 app.use(function * (next) {
18   var ctx = this
19
20   ctx.request
21   ctx.response
22
23   ctx.body = 'hello'
24
25   ctx.state.user = yield User.find(id).fetch()
26
27   ctx.cookies.set('foo', 'hello', { signed: true })
28   ctx.cookies.get('foo')
29
30   ctx.throw(403)
31 ```
32
33 ### Request
34
35 ```js
36   ctx.header        // ctx.headers
37   ctx.method        // and =
38   ctx.url           // and =
39   ctx.originalUrl
40   ctx.origin        // => 'http://example.com'
41   ctx.href          // => 'http://example.com/foo?q=hello'
42   ctx.path          // and =
43   ctx.query         // { q: 'hello' }
44   ctx.query         // and =
45   ctx.querystring
46   ctx.querystring   // and =
47   ctx.host
48   ctx.hostname
49   ctx.fresh
50   ctx.stale
51   ctx.socket
52   ctx.protocol
53   ctx.secure
54   ctx.ip
55   ctx.ips
56   ctx.subdomains
57   ctx.is()                  // .is('html') .is('text/html')
58   ctx.accepts()             // .accepts('html') .accepts('html', 'json')
59   ctx.acceptsEncodings()    // .acceptsEncodings('gzip')
60   ctx.acceptsCharsets()
61   ctx.acceptsLanguages()
62   ctx.get()
63
64   ctx.request.type          // => 'image/jpg'
65   ctx.request.charset       // => 'utf-8'
66   ctx.request.protocol      // => 'https'
67   ctx.request.secure        // => true
68   ctx.request.ip            // (supports X-Forwarded-For if app.proxy)
69   ctx.request.ips
70   ctx.request.subdomains
71
72   ctx.request.fresh
73   ctx.request.stale
74 ```
75
76 ### Response
77
78 ```js
79   ctx.body = 'hello'
80
81   ctx.throw(403)
82   ctx.throw('name required', 403)
83   ctx.throw(403, 'name required')
84   ctx.throw('oops')
85   ctx.assert(ctx.state.user, 401, 'You must log in')
86 ```
87
88 ### Middlewares
89
90 ```js
91 exports.conditionalGet = require('koa-conditional-get');
92 exports.responseTime = require('koa-response-time');
93 exports.ratelimit = require('koa-ratelimit');
94 exports.compress = require('koa-compress');
95 exports.rewrite = require('koa-rewrite');
96 exports.favicon = require('koa-favicon');
97 exports.session = require('koa-session');
98 exports.static = require('koa-static');
99 exports.logger = require('koa-logger');
100 exports.mount = require('koa-mount');
101 exports.etag = require('koa-etag');
102 ```