OSDN Git Service

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