Skip to content

Commit

Permalink
Handle OPTIONS requests to spec (#48)
Browse files Browse the repository at this point in the history
* add successful response for OPTIONS requests without calling inner callback
  • Loading branch information
infernalmaster authored and tim-phillips committed Dec 24, 2018
1 parent 14ec915 commit 34c44b0
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,7 @@ default: `86400`
##### `origin`

default: `*`

##### `runHandlerOnOptionsRequest`

default: `false`
9 changes: 7 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ const cors = (options = {}) => handler => (req, res, ...restArgs) => {
allowMethods = DEFAULT_ALLOW_METHODS,
allowHeaders = DEFAULT_ALLOW_HEADERS,
allowCredentials = true,
exposeHeaders = []
exposeHeaders = [],
runHandlerOnOptionsRequest = false
} = options

res.setHeader('Access-Control-Allow-Origin', origin)
Expand All @@ -43,7 +44,11 @@ const cors = (options = {}) => handler => (req, res, ...restArgs) => {
res.setHeader('Access-Control-Max-Age', String(maxAge))
}

return handler(req, res, ...restArgs)
if (preFlight && !runHandlerOnOptionsRequest) {
res.end()
} else {
return handler(req, res, ...restArgs)
}
}

module.exports = cors
33 changes: 27 additions & 6 deletions src/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,18 +228,39 @@ test('allows remove allow credentials header', async t => {
}
})

test('responds to OPTIONS requests', async t => {
test('responds to OPTIONS requests without running handler', async t => {
const cors = microCors()
const router = micro(cors(() => ({})))
let isHandlerCalled = false
const router = micro(cors((req, res) => {
isHandlerCalled = true
res.end()
}))
const url = await listen(router)
const method = 'OPTIONS'

const response = await request({
url,
method,
method: 'OPTIONS',
...testRequestOptions
})

t.is(response.statusCode, 200)
t.false(isHandlerCalled)
})

test('allows to run handler on OPTIONS request', async t => {
const cors = microCors({ runHandlerOnOptionsRequest: true })
let isHandlerCalled = false
const router = micro(cors((req, res) => {
isHandlerCalled = true
res.end()
}))
const url = await listen(router)

await request({
url,
method: 'OPTIONS',
...testRequestOptions
})

t.deepEqual(200, response.statusCode)
t.deepEqual({}, response.body)
t.true(isHandlerCalled)
})

0 comments on commit 34c44b0

Please sign in to comment.