Update 'Using CORS in Express'

master
Mehran Dehghanian 4 years ago
parent e16bbff161
commit 284c3f0ff9

@ -24,3 +24,56 @@ If you make a request to your app, you will notice a new header being returned:
`Access-Control-Allow-Origin: *` `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). The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).
### Restricting allowed hosts
If you want to restrict AJAX access to a single origin, you can use the origin option:
```
app.use(cors({
origin: 'http://yourapp.com'
}));
```
If you would rather have a list of allowed origins, you can use a function instead of a string as the origin value:
```
var allowedOrigins = ['http://localhost:3000',
'http://yourapp.com'];
app.use(cors({
origin: function(origin, callback){
// allow requests with no origin
// (like mobile apps or curl requests)
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
```
If you make a new request to the server, you will notice the Access-Control-Allow-Origin header now returns the value of the origin making the request:
`Access-Control-Allow-Origin: http://localhost:3000`
### Sending custom headers
By default, only 6 response headers are exposed over CORS:
* Cache-Control
* Content-Language
* Content-Type
* Expires
* Last-Modified
* Pragma
If you want to expose other headers, you can use the exposedHeaders option:
```
app.use(cors({
exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}));
```
You will notice your server responses now include an additional Access-Control-Expose-Headers
header:
`Access-Control-Expose-Headers: Content-Length,X-Foo,X-Bar`
### More
read more on :https://medium.com/zero-equals-false/using-cors-in-express-cac7e29b005b#:~:text=Enabling%20CORS,using%20the%20cors%20npm%20module.&text=That's%20it.,CORS%20is%20now%20enabled.&text=The%20Access%2DControl%2DAllow%2D,allows%20access%20from%20any%20origin).
Loading…
Cancel
Save