UNPKG

6.93 kBMarkdownView Raw
1# `cors`
2
3CORS is a node.js package for providing a [Connect](http://www.senchalabs.org/connect/)/[Express](http://expressjs.com/) middleware that can be used to enable [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) with various options.
4
5**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)**
6
7[![NPM](https://nodei.co/npm/cors.png?downloads=true&stars=true)](https://nodei.co/npm/cors/)
8
9[![build status](https://secure.travis-ci.org/troygoode/node-cors.png)](http://travis-ci.org/troygoode/node-cors)
10* [Installation](#installation)
11* [Usage](#usage)
12 * [Simple Usage](#simple-usage-enable-all-cors-requests)
13 * [Enable CORS for a Single Route](#enable-cors-for-a-single-route)
14 * [Configuring CORS](#configuring-cors)
15 * [Configuring CORS Asynchronously](#configuring-cors-asynchronously)
16 * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)
17* [Configuration Options](#configuration-options)
18* [Demo](#demo)
19* [License](#license)
20* [Author](#author)
21
22## Installation (via [npm](https://npmjs.org/package/cors))
23
24```bash
25$ npm install cors
26```
27
28## Usage
29
30### Simple Usage (Enable *All* CORS Requests)
31
32```javascript
33var express = require('express')
34 , cors = require('cors')
35 , app = express();
36
37app.use(cors());
38app.use(app.router);
39
40app.get('/products/:id', function(req, res, next){
41 res.json({msg: 'This is CORS-enabled for all origins!'});
42});
43
44app.listen(80, function(){
45 console.log('CORS-enabled web server listening on port 80');
46});
47```
48
49### Enable CORS for a Single Route
50
51```javascript
52var express = require('express')
53 , cors = require('cors')
54 , app = express();
55
56app.get('/products/:id', cors(), function(req, res, next){
57 res.json({msg: 'This is CORS-enabled for all origins!'});
58});
59
60app.listen(80, function(){
61 console.log('CORS-enabled web server listening on port 80');
62});
63```
64
65### Configuring CORS
66
67```javascript
68var express = require('express')
69 , cors = require('cors')
70 , app = express();
71
72var corsOptions = {
73 origin: 'http://example.com'
74};
75
76app.get('/products/:id', cors(corsOptions), function(req, res, next){
77 res.json({msg: 'This is CORS-enabled for only example.com.'});
78});
79
80app.listen(80, function(){
81 console.log('CORS-enabled web server listening on port 80');
82});
83```
84
85### Configuring CORS w/ Dynamic Origin
86
87```javascript
88var express = require('express')
89 , cors = require('cors')
90 , app = express();
91
92var whitelist = ['http://example1.com', 'http://example2.com'];
93var corsOptions = {
94 origin: function(origin, callback){
95 var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
96 callback(null, originIsWhitelisted);
97 }
98};
99
100app.get('/products/:id', cors(corsOptions), function(req, res, next){
101 res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
102});
103
104app.listen(80, function(){
105 console.log('CORS-enabled web server listening on port 80');
106});
107```
108
109### Enabling CORS Pre-Flight
110
111Certain CORS requests are considered 'complex' and require an initial
112`OPTIONS` request (called the "pre-flight request"). An example of a
113'complex' CORS request is one that uses an HTTP verb other than
114GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable
115pre-flighting, you must add a new OPTIONS handler for the route you want
116to support:
117
118```javascript
119var express = require('express')
120 , cors = require('cors')
121 , app = express();
122
123app.options('/products/:id', cors()); // enable pre-flight request for DELETE request
124app.del('/products/:id', cors(), function(req, res, next){
125 res.json({msg: 'This is CORS-enabled for all origins!'});
126});
127
128app.listen(80, function(){
129 console.log('CORS-enabled web server listening on port 80');
130});
131```
132
133You can also enable pre-flight across-the-board like so:
134
135```
136app.options('*', cors()); // include before other routes
137```
138
139### Configuring CORS Asynchronously
140
141```javascript
142var express = require('express')
143 , cors = require('cors')
144 , app = express();
145
146var whitelist = ['http://example1.com', 'http://example2.com'];
147var corsOptionsDelegate = function(req, callback){
148 var corsOptions;
149 if(whitelist.indexOf(req.header('Origin')) !== -1){
150 corsOptions = { origin: true }; // reflect (enable) the requested origin in the CORS response
151 }else{
152 corsOptions = { origin: false }; // disable CORS for this request
153 }
154 callback(null, corsOptions); // callback expects two parameters: error and options
155};
156
157app.get('/products/:id', cors(corsOptionsDelegate), function(req, res, next){
158 res.json({msg: 'This is CORS-enabled for a whitelisted domain.'});
159});
160
161app.listen(80, function(){
162 console.log('CORS-enabled web server listening on port 80');
163});
164```
165
166## Configuration Options
167
168* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Expects a string (ex: "http://example.com"). Set to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`. Set to `false` to disable CORS. Can also be set to a function, which takes the request origin as the first parameter and a callback (which expects the signature `err [object], allow [bool]`) as the second.
169* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`).
170* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization]`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header.
171* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range]`). If not specified, no custom headers are exposed.
172* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.
173* `maxAge`: Configures the **Access-Control-Allow-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted.
174
175For details on the effect of each CORS header, [read this article on HTML5 Rocks](http://www.html5rocks.com/en/tutorials/cors/).
176
177## Demo
178
179A demo that illustrates CORS working (and not working) using jQuery is available here: [http://node-cors-client.herokuapp.com/](http://node-cors-client.herokuapp.com/)
180
181Code for that demo can be found here:
182
183* Client: [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client)
184* Server: [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server)
185
186## License
187
188[MIT License](http://www.opensource.org/licenses/mit-license.php)
189
190## Author
191
192[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))