Skip to content

Commit

Permalink
fix: should set OPTIONS on access-control-allow-methods (#608)
Browse files Browse the repository at this point in the history
Access to fetch at
'https://registry.npmmirror.com/isstream/-/isstream-0.1.0.tgz' from
origin 'https://foo.com' has been blocked by CORS policy: Method OPTIONS
is not allowed by Access-Control-Allow-Methods in preflight response.
  • Loading branch information
fengmk2 committed Nov 3, 2023
1 parent f03d48e commit 0179ef3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
2 changes: 2 additions & 0 deletions config/config.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export default (appInfo: EggAppConfig) => {
return ctx.get('Origin');
},
credentials: true,
// https://github.com/koajs/cors/blob/master/index.js#L10C57-L10C64
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
};

config.nfs = {
Expand Down
22 changes: 12 additions & 10 deletions test/port/controller/HomeController/cors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ describe('test/port/controller/HomeController/cors.test.ts', () => {
const res = await app.httpRequest()
.get('/-/ping')
.set('origin', 'https://www.test-cors.org');
assert(res.status === 200);
assert(res.body.pong === true);
assert(res.headers.vary === 'Origin');
assert(res.headers['access-control-allow-origin'] === 'https://www.test-cors.org');
assert(res.headers['access-control-allow-credentials'] === 'true');
assert.equal(res.status, 200);
assert.equal(res.body.pong, true);
assert.equal(res.headers.vary, 'Origin');
assert.equal(res.headers['access-control-allow-origin'], 'https://www.test-cors.org');
assert.equal(res.headers['access-control-allow-credentials'], 'true');
assert(!res.headers['access-control-allow-methods']);
});

it('should OPTIONS work', async () => {
Expand All @@ -20,11 +21,12 @@ describe('test/port/controller/HomeController/cors.test.ts', () => {
.set('origin', 'https://www.test-cors.org/foo')
.set('Access-Control-Request-Method', 'OPTIONS')
.set('Access-Control-Request-Headers', 'authorization');
assert(res.status === 204);
assert(res.headers.vary === 'Origin');
assert(res.headers['access-control-allow-origin'] === 'https://www.test-cors.org/foo');
assert(res.headers['access-control-allow-credentials'] === 'true');
assert(res.headers['access-control-allow-headers'] === 'authorization');
assert.equal(res.status, 204);
assert.equal(res.headers.vary, 'Origin');
assert.equal(res.headers['access-control-allow-origin'], 'https://www.test-cors.org/foo');
assert.equal(res.headers['access-control-allow-credentials'], 'true');
assert.equal(res.headers['access-control-allow-headers'], 'authorization');
assert.equal(res.headers['access-control-allow-methods'], 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS');
});
});
});

0 comments on commit 0179ef3

Please sign in to comment.