diff --git a/README.md b/README.md index 882da6b..dcc2ea1 100644 --- a/README.md +++ b/README.md @@ -60,3 +60,7 @@ default: `86400` ##### `origin` default: `*` + +##### `runHandlerOnOptionsRequest` + +default: `false` diff --git a/src/index.js b/src/index.js index baf3cd0..1f58a7c 100644 --- a/src/index.js +++ b/src/index.js @@ -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) @@ -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 diff --git a/src/test.js b/src/test.js index e3b7199..c5c5fbb 100644 --- a/src/test.js +++ b/src/test.js @@ -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) })