|
|
@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
### Using CORS in Express
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Cross-origin resource sharing (CORS) allows AJAX requests to skip the Same-origin policy and access resources from remote hosts.
|
|
|
|
|
|
|
|
In this post I will show you how to enable CORS support in Express. I will also provide some tips to handle common use cases that come up when working with Single Page Applications, like exposing HTTP sessions and custom headers.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
### Enabling CORS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The easiest way to get CORS working in Express is by using the cors npm module.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
You can simply add it as a dependency:
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
npm install --save cors
|
|
|
|
|
|
|
|
And then use it as middleware:
|
|
|
|
|
|
|
|
var express = require('express');
|
|
|
|
|
|
|
|
var cors = require('cors');
|
|
|
|
|
|
|
|
var app = express();
|
|
|
|
|
|
|
|
app.use(cors());
|
|
|
|
|
|
|
|
/* your regular routes go here */
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
That’s it. CORS is now enabled.
|
|
|
|
|
|
|
|
If you make a request to your app, you will notice a new header being returned:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
`Access-Control-Allow-Origin: *`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).
|