Skip to content

Commit 145b2c3

Browse files
committed
first commit
0 parents  commit 145b2c3

File tree

5 files changed

+216
-0
lines changed

5 files changed

+216
-0
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
2+
yarn.lock
3+
4+
node_modules/

README.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# kelp-cors
2+
3+
[Cross-Origin Resource Sharing(CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) Middleware for [Kelp Project](https://github.com/kelpjs).
4+
5+
## Installation
6+
7+
```bash
8+
$ npm i kelp-cors --save
9+
```
10+
11+
## Example
12+
13+
```js
14+
const http = require('http');
15+
const kelp = require('kelp');
16+
const cors = require('kelp-cors');
17+
18+
const app = kelp();
19+
20+
app.use(cors({
21+
allowOrigin: 'baidu.com',
22+
allowMethods: ['POST', 'GET'],
23+
allowHeaders: ['X-MY-HEADER', 'X-Y-HEADER'],
24+
exposeHeaders: ['X-MY-HEADER'],
25+
maxAge: 3600,
26+
allowCredentials: true,
27+
}));
28+
29+
app.use((req, res) => {
30+
res.end("hello world");
31+
});
32+
33+
http.createServer(app).listen(3000);
34+
```
35+
36+
Also accept function as options:
37+
38+
```js
39+
app.use(cors(({ preflight }) => {
40+
console.log('preflight:', preflight);
41+
return { alloworigin: '*', allowcredentials: false };
42+
}));
43+
```
44+
45+
## Contributing
46+
47+
+ Fork this Repo first
48+
+ Clone your Repo
49+
+ Install dependencies by $ npm install
50+
+ Checkout a feature branch
51+
+ Feel free to add your features
52+
+ Make sure your features are fully tested
53+
+ Publish your local branch, Open a pull request
54+
+ Enjoy hacking <3
55+
56+
57+
## MIT license
58+
59+
Copyright (c) 2016 Lsong <song940@gmail.com>
60+
61+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
62+
63+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
64+
65+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

example/index.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const http = require('http');
2+
const kelp = require('kelp');
3+
const cors = require('..');
4+
5+
const app = kelp();
6+
7+
app.use(cors({
8+
allowOrigin: 'baidu.com',
9+
allowMethods: ['POST', 'GET'],
10+
allowHeaders: ['X-MY-HEADER', 'X-Y-HEADER'],
11+
exposeHeaders: ['X-MY-HEADER'],
12+
maxAge: 3600,
13+
allowCredentials: true,
14+
}));
15+
16+
// app.use(cors(({ preflight }) => {
17+
// console.log('preflight:', preflight);
18+
// return { allowOrigin: '*', allowCredentials: false };
19+
// }));
20+
21+
app.use((req, res) => {
22+
res.end("hello world");
23+
});
24+
25+
http.createServer(app).listen(3000);

index.js

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
const assert = require('assert');
2+
3+
const defaultAllowMethods = 'GET,HEAD,PUT,POST,DELETE,PATCH';
4+
5+
const split = str => {
6+
if (!str) return [];
7+
return str.split(',');
8+
};
9+
10+
const getHeader = (req, name) => {
11+
const key = name.toLowerCase();
12+
return req.headers[key];
13+
};
14+
15+
/**
16+
* kelp-cors middleware
17+
* @docs https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
18+
* @param {*} options
19+
* @returns
20+
*/
21+
const cors = (options = {}) => {
22+
const flag = typeof options === 'function';
23+
/**
24+
* kelp middleware
25+
*/
26+
return async (req, res, next) => {
27+
res.headers = res.headers || {};
28+
let preflight = false, requestHeaders, requestMethod;
29+
const requestOrigin = getHeader(req, 'Origin');
30+
if (!requestOrigin) return next();
31+
if (req.method === 'OPTIONS') {
32+
preflight = true; // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests
33+
requestMethod = getHeader(req, 'Access-Control-Request-Method');
34+
requestHeaders = getHeader(req, 'Access-Control-Request-Headers');
35+
if (!requestMethod) return next(); // not a valid preflight request
36+
}
37+
/**
38+
* process allow* settings
39+
*/
40+
let {
41+
allowOrigin = requestOrigin,
42+
allowMethods = defaultAllowMethods,
43+
allowHeaders = requestHeaders,
44+
allowCredentials = true,
45+
exposeHeaders, maxAge,
46+
} = flag ? await options({
47+
preflight,
48+
requestMethod,
49+
requestOrigin,
50+
requestHeaders: split(requestHeaders),
51+
}) : options;
52+
/**
53+
* serialized
54+
*/
55+
if (Array.isArray(allowMethods)) allowMethods = allowMethods.join(',');
56+
if (Array.isArray(allowHeaders)) allowHeaders = allowHeaders.join(',');
57+
if (Array.isArray(exposeHeaders)) exposeHeaders = exposeHeaders.join(',');
58+
/**
59+
* Please note that, when responding to a credentialed requests request,
60+
* the server must specify an origin in the value of the Access-Control-Allow-Origin header,
61+
* instead of specifying the "*" wildcard.
62+
* @docs https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#requests_with_credentials
63+
*/
64+
if (allowCredentials === true) {
65+
assert.notEqual(allowOrigin, '*', '[kelp-cors] Must specify an origin instead of specifying the "*" wildcard when responding allowCredentials.');
66+
}
67+
/**
68+
* If the server specifies a single origin (that may dynamically change
69+
* based on the requesting origin as part of a allowlist) rather than the "*" wildcard,
70+
* then the server should also include Origin in the Vary response header —
71+
* to indicate to clients that server responses will differ based on the value of the Origin request header.
72+
*/
73+
if (allowOrigin !== '*') {
74+
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary
75+
const vary = split(res.headers['vary']);
76+
// also include ',Origin' in the 'Vary'
77+
if (vary.indexOf('Origin') === -1)
78+
res.setHeader('Vary', vary.concat('Origin').join(','));
79+
}
80+
res.setHeader('Access-Control-Allow-Origin', allowOrigin);
81+
if (maxAge) res.setHeader('Access-Control-Max-Age', maxAge);
82+
if (allowCredentials) res.setHeader('Access-Control-Allow-Credentials', 'true');
83+
if (preflight) {
84+
if (allowMethods) res.setHeader('Access-Control-Allow-Methods', allowMethods);
85+
if (allowHeaders) res.setHeader('Access-Control-Allow-Headers', allowHeaders);
86+
res.end();
87+
return;
88+
} else {
89+
// @docs https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#access-control-expose-headers
90+
if (exposeHeaders) res.setHeader('Access-Control-Expose-Headers', exposeHeaders);
91+
}
92+
return next();
93+
};
94+
};
95+
96+
module.exports = cors;

package.json

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"name": "kelp-cors",
3+
"version": "0.0.0",
4+
"description": "Cross-Origin Resource Sharing(CORS) Middleware for Kelp Project.",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/song940/kelp-cors.git"
12+
},
13+
"keywords": [
14+
"kelp",
15+
"cors"
16+
],
17+
"author": "Lsong <song940@gmail.com>",
18+
"license": "MIT",
19+
"bugs": {
20+
"url": "https://github.com/song940/kelp-cors/issues"
21+
},
22+
"homepage": "https://github.com/song940/kelp-cors#readme",
23+
"devDependencies": {
24+
"kelp": "^2.0.2"
25+
}
26+
}

0 commit comments

Comments
 (0)