Skip to content

Commit

Permalink
Merge 85ac686 into 5cccf75
Browse files Browse the repository at this point in the history
  • Loading branch information
shackpank committed Jun 19, 2019
2 parents 5cccf75 + 85ac686 commit e7181c2
Showing 1 changed file with 10 additions and 19 deletions.
29 changes: 10 additions & 19 deletions README.md
Expand Up @@ -91,6 +91,12 @@ app.listen(80, function () {

### Configuring CORS w/ Dynamic Origin

Provide an `origin` function, which will be passed a string `origin` containing the origin domain, and a `callback` expecting `(err, ok)`.

If you callback with `(null, true)`, the incoming origin will be echoed back in the access-control-allow-origin header, permitting browser acces to the resource. Callback with `(null, false)` and it won't, and the browser will abort the cross-origin request.

Calling back with an error should be avoided, unless you really mean to block all access to your server from the passed origin - it will halt the request and return an error to the client, which ends up rejecting same-origin requests and requests from non-browser clients like curl or Postman if you're following a typical 'whitelist' approach.

```javascript
var express = require('express')
var cors = require('cors')
Expand All @@ -99,11 +105,11 @@ var app = express()
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
if (origin === 'http://evil.com') {
return callback(new Error('Unauthorized'))
}

callback(null, whitelist.indexOf(origin) !== -1)
}
}

Expand All @@ -116,21 +122,6 @@ app.listen(80, function () {
})
```

If you do not want to block REST tools or server-to-server requests,
add a `!origin` check in the origin function like so:

```javascript
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
```

### Enabling CORS Pre-Flight

Certain CORS requests are considered 'complex' and require an initial
Expand Down

0 comments on commit e7181c2

Please sign in to comment.