1 | # koa2-cors
|
2 |
|
3 | ## install
|
4 |
|
5 | ```bash
|
6 | npm install --save koa2-cors
|
7 | ```
|
8 |
|
9 | ## Usage
|
10 |
|
11 | ```js
|
12 | var koa = require('koa');
|
13 | var cors = require('koa2-cors');
|
14 |
|
15 | var app = koa();
|
16 | app.use(cors());
|
17 | ```
|
18 |
|
19 | ## Options
|
20 |
|
21 | ### origin
|
22 |
|
23 | Configures the **Access-Control-Allow-Origin** CORS header. expects a string. Can also be set to a function, which takes the `ctx` as the first parameter.
|
24 |
|
25 | ### exposeHeaders
|
26 |
|
27 | Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited array.
|
28 |
|
29 | ### maxAge
|
30 |
|
31 | Configures the **Access-Control-Max-Age** CORS header. Expects a
|
32 | Number.
|
33 |
|
34 | ### credentials
|
35 |
|
36 | Configures the **Access-Control-Allow-Credentials** CORS header. Expects a Boolean.
|
37 |
|
38 | ### allowMethods
|
39 |
|
40 | Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited array , If not specified, default allowMethods is `['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']`.
|
41 |
|
42 | ### allowHeaders
|
43 | Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited array . If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header.
|
44 |
|
45 | ```js
|
46 | var koa = require('koa');
|
47 | var cors = require('koa2-cors');
|
48 |
|
49 | var app = koa();
|
50 | app.use(cors({
|
51 | origin: function(ctx) {
|
52 | if (ctx.url === '/test') {
|
53 | return false;
|
54 | }
|
55 | return '*';
|
56 | },
|
57 | exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
|
58 | maxAge: 5,
|
59 | credentials: true,
|
60 | allowMethods: ['GET', 'POST', 'DELETE'],
|
61 | allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
|
62 | }));
|
63 | ...
|
64 | ```
|
65 |
|
66 | [More details about CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).
|
67 |
|
68 | ## License
|
69 |
|
70 | [MIT License](http://www.opensource.org/licenses/mit-license.php)
|