Skip to content

Commit

Permalink
Don't forward OPTIONS requests (#4)
Browse files Browse the repository at this point in the history
* Update micro-cors

* Don't forward OPTIONS requests
  • Loading branch information
DeltaEvo authored and billiegoose committed Sep 20, 2018
1 parent 4de612c commit 4fa1141
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 34 deletions.
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ async function service (req, res) {
// Don't waste my precious bandwidth
return send(res, 403, '')
}
if (req.method === 'OPTIONS') {
return send(res, 200, '')
}

let headers = {}
for (let h of allowHeaders) {
Expand Down
52 changes: 18 additions & 34 deletions micro-cors.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,43 +20,27 @@ const DEFAULT_ALLOW_HEADERS = [

const DEFAULT_MAX_AGE_SECONDS = 60 * 60 * 24 // 24 hours

const cors = options => handler => (req, res, ...restArgs) => {
const cors = (options = {}) => handler => (req, res, ...restArgs) => {
const {
maxAge,
origin,
allowHeaders,
exposeHeaders,
allowMethods
} = (options || {})

res.setHeader(
'Access-Control-Max-Age',
'' + (maxAge || DEFAULT_MAX_AGE_SECONDS)
)

res.setHeader(
'Access-Control-Allow-Origin',
(origin || '*')
)

res.setHeader(
'Access-Control-Allow-Methods',
(allowMethods || DEFAULT_ALLOW_METHODS).join(',')
)

res.setHeader(
'Access-Control-Allow-Headers',
(allowHeaders || DEFAULT_ALLOW_HEADERS).join(',')
)

if (exposeHeaders && exposeHeaders.length) {
res.setHeader(
'Access-Control-Expose-Headers',
exposeHeaders.join(',')
)
origin = '*',
maxAge = DEFAULT_MAX_AGE_SECONDS,
allowMethods = DEFAULT_ALLOW_METHODS,
allowHeaders = DEFAULT_ALLOW_HEADERS,
exposeHeaders = []
} = options

res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')
if (exposeHeaders.length) {
res.setHeader('Access-Control-Expose-Headers', exposeHeaders.join(','))
}

res.setHeader('Access-Control-Allow-Credentials', 'true')
const preFlight = req.method === 'OPTIONS'
if (preFlight) {
res.setHeader('Access-Control-Allow-Methods', allowMethods.join(','))
res.setHeader('Access-Control-Allow-Headers', allowHeaders.join(','))
res.setHeader('Access-Control-Max-Age', String(maxAge))
}

return handler(req, res, ...restArgs)
}
Expand Down

0 comments on commit 4fa1141

Please sign in to comment.