Easily handle HTTP Access Control (CORS) in your applications
npm install access-control
access-control implements HTTP Access Control, which more commonly known as
CORS according to the W3 specification. The code is dead simple, easy to
understand and therefor also easy to contribute to. access-control comes with
a really simple API, so it's super simple, super awesome, super stable. All you
expect from a small building block module as this.
```
npm install --save access-control
The module must first be configured before it can be used to add the correct
CORS information to your HTTP requests. This is done by suppling the module with
options.
`js
'use strict';
var access = require('access-control');
`
After requiring the module you can supply the returned function with an options
object which can contain the following properties:
* whichtrue (which is also the default value) inorigins option to set to * weAccess-Control-Allow-OriginOrigin header. As * as origintrue as value is not allowed by theOPTIONS request. The value can be set in numbers or a human`js`
var cors = access({
maxAge: '1 hour',
credentials: true,
origins: 'http://example.com'
});
Now the cors variable contains a function that should receive your requestresponse
and . So it's as easy as:
`js
var http = require('http').createServer(function (req, res) {
if (cors(req, res)) return;
res.end('hello world');
}).listen(8080);
`
You might have noticed that we've added an if statement around our corstrue
function call. This is because the module will be answering the preflight
request for you. So when it returns the boolean you don't have to403 Forbidden
respond the request any more. In addition to the answering the option request is
also answer the requests with a when the validation of the
Access Control is failing.
In order to not waste to much bandwidth, the CORS headers will only be added if
the request contains an Origin header, which should be sent by every request
that requires HTTP Access Control information.
The library has build-in support for express based middleware (req, res, next).
In fact, it's build in to the returned function so all you need to do is:
`js
var app = express();
app.use(require('access-control')({ / options here / }));
`
And you have CORS handling enabled on your express instance. It's that easy.
If you're using Phonegap, your XHR requests will be sent with Origin: null` as
Origin header. In order to resolve this you must add the domain you are
requesting to your origin white list:
http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
This will ensure that the correct headers will be used for these cross
domain/origin requests.
If you're interested in learning more about HTTP Access Control (CORS) here's a
good list to get started with:
- W3C's CORS Spec
- HTML5 Rocks CORS Tutorial
- Mozilla's HTTP access control (CORS)
- Mozilla's Server-Side Access Control
- Enable CORS
- Same origin policy
MIT