1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | module.exports = function crossOrigin(options = {}) {
|
15 | const defaultOptions = {
|
16 | allowMethods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
|
17 | };
|
18 |
|
19 |
|
20 | for (let key in defaultOptions) {
|
21 | if (!Object.prototype.hasOwnProperty.call(options, key)) {
|
22 | options[key] = defaultOptions[key];
|
23 | }
|
24 | }
|
25 |
|
26 | return async function (ctx, next) {
|
27 | let origin;
|
28 | if (typeof options.origin === 'function') {
|
29 | origin = options.origin(ctx);
|
30 | } else {
|
31 | origin = options.origin || ctx.get('Origin') || '*';
|
32 | }
|
33 | if (!origin) {
|
34 | return await next();
|
35 | }
|
36 |
|
37 |
|
38 | ctx.set('Access-Control-Allow-Origin', origin);
|
39 |
|
40 | if (ctx.method === 'OPTIONS') {
|
41 |
|
42 | if (!ctx.get('Access-Control-Request-Method')) {
|
43 | return await next();
|
44 | }
|
45 |
|
46 |
|
47 | if (options.maxAge) {
|
48 | ctx.set('Access-Control-Max-Age', String(options.maxAge));
|
49 | }
|
50 |
|
51 |
|
52 | if (options.credentials === true) {
|
53 |
|
54 |
|
55 | ctx.set('Access-Control-Allow-Credentials', 'true');
|
56 | }
|
57 |
|
58 |
|
59 | if (options.allowMethods) {
|
60 | ctx.set('Access-Control-Allow-Methods', options.allowMethods.join(','));
|
61 | }
|
62 |
|
63 |
|
64 | if (options.allowHeaders) {
|
65 | ctx.set('Access-Control-Allow-Headers', options.allowHeaders.join(','));
|
66 | } else {
|
67 | ctx.set('Access-Control-Allow-Headers', ctx.get('Access-Control-Request-Headers'));
|
68 | }
|
69 |
|
70 | ctx.status = 204;
|
71 | } else {
|
72 |
|
73 |
|
74 | if (options.credentials === true) {
|
75 | if (origin === '*') {
|
76 |
|
77 | ctx.remove('Access-Control-Allow-Credentials');
|
78 | } else {
|
79 | ctx.set('Access-Control-Allow-Credentials', 'true');
|
80 | }
|
81 | }
|
82 |
|
83 |
|
84 | if (options.exposeHeaders) {
|
85 | ctx.set('Access-Control-Expose-Headers', options.exposeHeaders.join(','));
|
86 | }
|
87 |
|
88 | try {
|
89 | await next();
|
90 | } catch (err) {
|
91 | throw err;
|
92 | }
|
93 | }
|
94 | };
|
95 | };
|