Skip to content

Commit

Permalink
fix(lambda): Set Cors header on GET requests (#865)
Browse files Browse the repository at this point in the history
  • Loading branch information
Geoff Jacobsen authored Jul 6, 2020
1 parent c3c4cdf commit c3e3c4c
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
2 changes: 2 additions & 0 deletions packages/lambda/src/__test__/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { LambdaContext } from '../lambda.context';
import { LambdaHttpResponse } from '../lambda.response';
import { Router } from '../router';
import { FakeLogger } from './log.spy';
import { HttpHeader } from '../header';

o.spec('router', () => {
function makeContext(httpMethod: string, path: string): LambdaContext {
Expand All @@ -20,6 +21,7 @@ o.spec('router', () => {

o(response.status).equals(200);
o(response.statusDescription).equals('stub');
o(response.header(HttpHeader.Cors)).equals('*');
});

['delete', 'post', 'head', 'put'].forEach((method) => {
Expand Down
1 change: 1 addition & 0 deletions packages/lambda/src/header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export const HttpHeader = {
RateLimit: 'X-RateLimit-Limit',
RateCount: 'X-RateLimit-Count',
RateExpire: 'X-RateLimit-Expires',
Cors: 'Access-Control-Allow-Origin',
};
7 changes: 5 additions & 2 deletions packages/lambda/src/router.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { LambdaContext } from './lambda.context';
import { LambdaHttpResponse } from './lambda.response';
import { HttpHeader } from './header';

export type ReqCallback = (req: LambdaContext) => Promise<LambdaHttpResponse>;

Expand All @@ -10,7 +11,7 @@ export class Router {
// Allow cross origin requests
if (req.method === 'options') {
return new LambdaHttpResponse(200, 'Options', {
'Access-Control-Allow-Origin': '*',
[HttpHeader.Cors]: '*',
'Access-Control-Allow-Credentials': 'false',
'Access-Control-Allow-Methods': 'OPTIONS,GET,PUT,POST,DELETE',
});
Expand All @@ -26,7 +27,9 @@ export class Router {
return new LambdaHttpResponse(404, 'Not Found');
}

return await handler(req);
const response = await handler(req);
response.header(HttpHeader.Cors, '*');
return response;
}

get(path: string, handler: ReqCallback): void {
Expand Down

0 comments on commit c3e3c4c

Please sign in to comment.