1 | # cors
|
2 |
|
3 | [![NPM Version][npm-image]][npm-url]
|
4 | [![NPM Downloads][downloads-image]][downloads-url]
|
5 | [![Build Status][travis-image]][travis-url]
|
6 | [![Test Coverage][coveralls-image]][coveralls-url]
|
7 |
|
8 | CORS 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.
|
9 |
|
10 | **[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)**
|
11 |
|
12 | * [Installation](#installation)
|
13 | * [Usage](#usage)
|
14 | * [Simple Usage](#simple-usage-enable-all-cors-requests)
|
15 | * [Enable CORS for a Single Route](#enable-cors-for-a-single-route)
|
16 | * [Configuring CORS](#configuring-cors)
|
17 | * [Configuring CORS Asynchronously](#configuring-cors-asynchronously)
|
18 | * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)
|
19 | * [Configuration Options](#configuration-options)
|
20 | * [Demo](#demo)
|
21 | * [License](#license)
|
22 | * [Author](#author)
|
23 |
|
24 | ## Installation
|
25 |
|
26 | This is a [Node.js](https://nodejs.org/en/) module available through the
|
27 | [npm registry](https://www.npmjs.com/). Installation is done using the
|
28 | [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
|
29 |
|
30 | ```sh
|
31 | $ npm install cors
|
32 | ```
|
33 |
|
34 | ## Usage
|
35 |
|
36 | ### Simple Usage (Enable *All* CORS Requests)
|
37 |
|
38 | ```javascript
|
39 | var express = require('express')
|
40 | var cors = require('cors')
|
41 | var app = express()
|
42 |
|
43 | app.use(cors())
|
44 |
|
45 | app.get('/products/:id', function (req, res, next) {
|
46 | res.json({msg: 'This is CORS-enabled for all origins!'})
|
47 | })
|
48 |
|
49 | app.listen(80, function () {
|
50 | console.log('CORS-enabled web server listening on port 80')
|
51 | })
|
52 | ```
|
53 |
|
54 | ### Enable CORS for a Single Route
|
55 |
|
56 | ```javascript
|
57 | var express = require('express')
|
58 | var cors = require('cors')
|
59 | var app = express()
|
60 |
|
61 | app.get('/products/:id', cors(), function (req, res, next) {
|
62 | res.json({msg: 'This is CORS-enabled for a Single Route'})
|
63 | })
|
64 |
|
65 | app.listen(80, function () {
|
66 | console.log('CORS-enabled web server listening on port 80')
|
67 | })
|
68 | ```
|
69 |
|
70 | ### Configuring CORS
|
71 |
|
72 | ```javascript
|
73 | var express = require('express')
|
74 | var cors = require('cors')
|
75 | var app = express()
|
76 |
|
77 | var corsOptions = {
|
78 | origin: 'http://example.com',
|
79 | optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
|
80 | }
|
81 |
|
82 | app.get('/products/:id', cors(corsOptions), function (req, res, next) {
|
83 | res.json({msg: 'This is CORS-enabled for only example.com.'})
|
84 | })
|
85 |
|
86 | app.listen(80, function () {
|
87 | console.log('CORS-enabled web server listening on port 80')
|
88 | })
|
89 | ```
|
90 |
|
91 | ### Configuring CORS w/ Dynamic Origin
|
92 |
|
93 | ```javascript
|
94 | var express = require('express')
|
95 | var cors = require('cors')
|
96 | var app = express()
|
97 |
|
98 | var whitelist = ['http://example1.com', 'http://example2.com']
|
99 | var corsOptions = {
|
100 | origin: function (origin, callback) {
|
101 | if (whitelist.indexOf(origin) !== -1) {
|
102 | callback(null, true)
|
103 | } else {
|
104 | callback(new Error('Not allowed by CORS'))
|
105 | }
|
106 | }
|
107 | }
|
108 |
|
109 | app.get('/products/:id', cors(corsOptions), function (req, res, next) {
|
110 | res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
|
111 | })
|
112 |
|
113 | app.listen(80, function () {
|
114 | console.log('CORS-enabled web server listening on port 80')
|
115 | })
|
116 | ```
|
117 |
|
118 | If you do not want to block REST tools or server-to-server requests,
|
119 | add a `!origin` check in the origin function like so:
|
120 |
|
121 | ```javascript
|
122 | var corsOptions = {
|
123 | origin: function (origin, callback) {
|
124 | if (whitelist.indexOf(origin) !== -1 || !origin) {
|
125 | callback(null, true)
|
126 | } else {
|
127 | callback(new Error('Not allowed by CORS'))
|
128 | }
|
129 | }
|
130 | }
|
131 | ```
|
132 |
|
133 | ### Enabling CORS Pre-Flight
|
134 |
|
135 | Certain CORS requests are considered 'complex' and require an initial
|
136 | `OPTIONS` request (called the "pre-flight request"). An example of a
|
137 | 'complex' CORS request is one that uses an HTTP verb other than
|
138 | GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable
|
139 | pre-flighting, you must add a new OPTIONS handler for the route you want
|
140 | to support:
|
141 |
|
142 | ```javascript
|
143 | var express = require('express')
|
144 | var cors = require('cors')
|
145 | var app = express()
|
146 |
|
147 | app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
|
148 | app.del('/products/:id', cors(), function (req, res, next) {
|
149 | res.json({msg: 'This is CORS-enabled for all origins!'})
|
150 | })
|
151 |
|
152 | app.listen(80, function () {
|
153 | console.log('CORS-enabled web server listening on port 80')
|
154 | })
|
155 | ```
|
156 |
|
157 | You can also enable pre-flight across-the-board like so:
|
158 |
|
159 | ```javascript
|
160 | app.options('*', cors()) // include before other routes
|
161 | ```
|
162 |
|
163 | ### Configuring CORS Asynchronously
|
164 |
|
165 | ```javascript
|
166 | var express = require('express')
|
167 | var cors = require('cors')
|
168 | var app = express()
|
169 |
|
170 | var whitelist = ['http://example1.com', 'http://example2.com']
|
171 | var corsOptionsDelegate = function (req, callback) {
|
172 | var corsOptions;
|
173 | if (whitelist.indexOf(req.header('Origin')) !== -1) {
|
174 | corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
|
175 | } else {
|
176 | corsOptions = { origin: false } // disable CORS for this request
|
177 | }
|
178 | callback(null, corsOptions) // callback expects two parameters: error and options
|
179 | }
|
180 |
|
181 | app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
|
182 | res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
|
183 | })
|
184 |
|
185 | app.listen(80, function () {
|
186 | console.log('CORS-enabled web server listening on port 80')
|
187 | })
|
188 | ```
|
189 |
|
190 | ## Configuration Options
|
191 |
|
192 | * `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values:
|
193 | - `Boolean` - set `origin` to `true` to reflect the [request origin](http://tools.ietf.org/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS.
|
194 | - `String` - set `origin` to a specific origin. For example if you set it to `"http://example.com"` only requests from "http://example.com" will be allowed.
|
195 | - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com".
|
196 | - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com".
|
197 | - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature `err [object], allow [bool]`) as the second.
|
198 | * `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']`).
|
199 | * `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.
|
200 | * `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.
|
201 | * `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.
|
202 | * `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted.
|
203 | * `preflightContinue`: Pass the CORS preflight response to the next handler.
|
204 | * `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`.
|
205 |
|
206 | The default configuration is the equivalent of:
|
207 |
|
208 | ```json
|
209 | {
|
210 | "origin": "*",
|
211 | "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
|
212 | "preflightContinue": false,
|
213 | "optionsSuccessStatus": 204
|
214 | }
|
215 | ```
|
216 |
|
217 | For details on the effect of each CORS header, read [this](http://www.html5rocks.com/en/tutorials/cors/) article on HTML5 Rocks.
|
218 |
|
219 | ## Demo
|
220 |
|
221 | A 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/)
|
222 |
|
223 | Code for that demo can be found here:
|
224 |
|
225 | * Client: [https://github.com/TroyGoode/node-cors-client](https://github.com/TroyGoode/node-cors-client)
|
226 | * Server: [https://github.com/TroyGoode/node-cors-server](https://github.com/TroyGoode/node-cors-server)
|
227 |
|
228 | ## License
|
229 |
|
230 | [MIT License](http://www.opensource.org/licenses/mit-license.php)
|
231 |
|
232 | ## Author
|
233 |
|
234 | [Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))
|
235 |
|
236 | [coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg
|
237 | [coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master
|
238 | [downloads-image]: https://img.shields.io/npm/dm/cors.svg
|
239 | [downloads-url]: https://npmjs.org/package/cors
|
240 | [npm-image]: https://img.shields.io/npm/v/cors.svg
|
241 | [npm-url]: https://npmjs.org/package/cors
|
242 | [travis-image]: https://img.shields.io/travis/expressjs/cors/master.svg
|
243 | [travis-url]: https://travis-ci.org/expressjs/cors
|