Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 5 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,13 @@ module.exports = function(options) {
// https://github.com/rs/cors/issues/10
ctx.vary('Origin');

if (!requestOrigin) return await next();
if (!requestOrigin) return next();

let origin;
if (typeof options.origin === 'function') {
origin = options.origin(ctx);
if (origin instanceof Promise) origin = await origin;
if (!origin) return await next();
if (!origin) return next();
} else {
origin = options.origin || requestOrigin;
}
Expand All @@ -69,7 +69,7 @@ module.exports = function(options) {
headersSet[key] = value;
}

if (ctx.method !== 'OPTIONS') {
if (ctx.method !== 'OPTIONS' || !ctx.get('Access-Control-Request-Method')) {
// Simple Cross-Origin Request, Actual Request, and Redirects
set('Access-Control-Allow-Origin', origin);

Expand All @@ -81,9 +81,8 @@ module.exports = function(options) {
set('Access-Control-Expose-Headers', options.exposeHeaders);
}

if (!options.keepHeadersOnError) {
return await next();
}
if (!options.keepHeadersOnError) return next();

try {
return await next();
} catch (err) {
Expand All @@ -97,15 +96,6 @@ module.exports = function(options) {
}
} else {
// Preflight Request

// If there is no Access-Control-Request-Method header or if parsing failed,
// do not set any additional headers and terminate this set of steps.
// The request is outside the scope of this specification.
if (!ctx.get('Access-Control-Request-Method')) {
// this not preflight request, ignore it
return await next();
}

ctx.set('Access-Control-Allow-Origin', origin);

if (options.credentials === true) {
Expand Down
1 change: 1 addition & 0 deletions test/cors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ describe('cors.test.js', function() {
request(app.listen())
.options('/')
.set('Origin', 'http://koajs.com')
.expect('Access-Control-Allow-Origin', 'http://koajs.com')
.expect(200, done);
});

Expand Down