Skip to content

Commit 4826aa1

Browse files
committed
Set response cors headers according to serverless configuration
1 parent 41959b7 commit 4826aa1

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,8 @@ module.exports = function(options) {
9393
callbacks.push(executeLambdaCallback(func));
9494
// Setup endpoint
9595
if (e.cors) {
96-
httpConfig.eventHandler('options', path, [decorateAddCORSCallback(true), send200]);
97-
callbacks.unshift(decorateAddCORSCallback());
96+
httpConfig.eventHandler('options', path, [decorateAddCORSCallback(e.cors, true), send200]);
97+
callbacks.unshift(decorateAddCORSCallback(e.cors));
9898
}
9999
httpConfig.eventHandler(method, path, callbacks);
100100
}

lib/decorators-callbacks.js

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,24 @@ module.exports.decorateLambdaReqCallback = function(getPrincipalId) {
1818
};
1919
};
2020

21-
module.exports.decorateAddCORSCallback = function(isOptionMethod) {
21+
module.exports.decorateAddCORSCallback = function(corsOpts, isOptionMethod) {
22+
// TODO: get default cors options from variables
23+
const cors = {
24+
origins: ['*'],
25+
methods: ['GET', 'PUT', 'HEAD', 'PATCH', 'POST', 'DELETE', 'OPTIONS'],
26+
headers: ['Authorization', 'Content-Type', 'x-amz-date', 'x-amz-security-token']
27+
};
28+
if(corsOpts instanceof Object) {
29+
Object.assign(cors, corsOpts);
30+
} else if(corsOpts != true) {
31+
throw new Error('Invalid cors configuration!');
32+
}
2233
return function(req, res, next) {
2334
if(isOptionMethod) {
24-
res.header('Access-Control-Allow-Methods', 'GET,PUT,HEAD,PATCH,POST,DELETE,OPTIONS');
25-
res.header('Access-Control-Allow-Headers', 'Authorization,Content-Type,x-amz-date,x-amz-security-token');
35+
res.header('Access-Control-Allow-Methods', cors.methods.join(','));
36+
res.header('Access-Control-Allow-Headers', cors.headers.join(','));
2637
}
27-
res.header('Access-Control-Allow-Origin', '*');
38+
res.header('Access-Control-Allow-Origin', cors.origins.join(','));
2839
next();
2940
};
3041
};

0 commit comments

Comments
 (0)