-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathindex.js
122 lines (101 loc) · 2.41 KB
/
index.js
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
'use strict';
/**
* CORS middleware
*
* @param {Object} [options]
* @return {GeneratorFunction}
* @api public
*/
module.exports = function getMiddleware(options) {
options = options || {};
var defaults = {
origin: true,
methods: 'GET,HEAD,PUT,POST,DELETE'
};
// Set defaults
for (var key in defaults) {
if (!options.hasOwnProperty(key)) {
options[key] = defaults[key];
}
}
// Set expose
if (Array.isArray(options.expose)) {
options.expose = options.expose.join(',');
}
// Set maxAge
if (typeof options.maxAge === 'number') {
options.maxAge = options.maxAge.toString();
} else {
options.maxAge = null;
}
// Set methods
if (Array.isArray(options.methods)) {
options.methods = options.methods.join(',');
}
// Set headers
if (Array.isArray(options.headers)) {
options.headers = options.headers.join(',');
}
return function* cors(next) {
/**
* Access Control Allow Origin
*/
var origin;
if (typeof options.origin === 'string') {
origin = options.origin;
} else if (options.origin === true) {
origin = this.get('origin') || '*';
} else if (options.origin === false) {
origin = options.origin;
} else if (typeof options.origin === 'function') {
origin = options.origin(this.request);
}
if (origin === false) {
yield next;
return ;
}
this.set('Access-Control-Allow-Origin', origin);
/**
* Access Control Expose Headers
*/
if (options.expose) {
this.set('Access-Control-Expose-Headers', options.expose);
}
/**
* Access Control Max Age
*/
if (options.maxAge) {
this.set('Access-Control-Max-Age', options.maxAge);
}
/**
* Access Control Allow Credentials
*/
if (options.credentials === true) {
this.set('Access-Control-Allow-Credentials', 'true');
}
/**
* Access Control Allow Methods
*/
this.set('Access-Control-Allow-Methods', options.methods);
/**
* Access Control Allow Headers
*/
var headers;
if (options.headers) {
headers = options.headers;
} else {
headers = this.get('access-control-request-headers');
}
if (headers) {
this.set('Access-Control-Allow-Headers', headers);
}
/**
* Returns
*/
if (this.method === 'OPTIONS') {
this.status = 204;
} else {
yield next;
}
};
};