From b0d4e359f8067f083429bcdeb04f7c6c24e68606 Mon Sep 17 00:00:00 2001 From: Thibault RICHARD Date: Sun, 10 Oct 2021 02:33:01 +0200 Subject: [PATCH] Fix CORS issue with HTTP APIs --- src/constructs/aws/Upload.ts | 14 +++++++++++--- test/unit/upload.test.ts | 2 ++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/constructs/aws/Upload.ts b/src/constructs/aws/Upload.ts index 82a90428..89fe44d5 100644 --- a/src/constructs/aws/Upload.ts +++ b/src/constructs/aws/Upload.ts @@ -95,13 +95,20 @@ export class Upload extends AwsConstruct { httpApiId: Fn.ref(this.provider.naming.getHttpApiLogicalId()), }); + const lambdaProxyIntegration = new LambdaProxyIntegration({ + handler: this.function, + }); + this.route = new HttpRoute(this, "Route", { httpApi: this.httpApi, - integration: new LambdaProxyIntegration({ - handler: this.function, - }), + integration: lambdaProxyIntegration, routeKey: HttpRouteKey.with("/upload-url", HttpMethod.POST), }); + this.route = new HttpRoute(this, "CORSRoute", { + httpApi: this.httpApi, + integration: lambdaProxyIntegration, + routeKey: HttpRouteKey.with("/upload-url", HttpMethod.OPTIONS), + }); } if (resolvedConfiguration.apiGateway === "rest") { @@ -153,6 +160,7 @@ const crypto = require("crypto"); const s3 = new AWS.S3(); exports.handler = async (event) => { + if (event.requestContext?.http?.method === 'OPTIONS') return ""; const body = JSON.parse(event.body); const fileName = \`tmp/\${crypto.randomBytes(5).toString('hex')}-\${body.fileName}\`; diff --git a/test/unit/upload.test.ts b/test/unit/upload.test.ts index 19075e30..dc5fe2c4 100644 --- a/test/unit/upload.test.ts +++ b/test/unit/upload.test.ts @@ -28,6 +28,8 @@ describe("upload", () => { "uploadRouteuploadRoute2545F0B8PermissionCB079AC2", "uploadRouteHttpIntegration02104492e88c1940a1c8d0dbac532c8091C83E5A", httpApiRoute, + "uploadCORSRouteuploadCORSRouteA2C80313PermissionEA9DCB1F", + "uploadCORSRouteC21947AF", ]); }); it("should create all required resources with REST API", async () => {