Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - AWS CDK Enable CORS

Part of my cdk project is a Websocket that gets output of a StepFunction which is triggered by a POST Request. This whole workflow works in the aws console just as postman.

But if I try it over the frontend I receive a CORS error:

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have set up my CORS options like this:

const api = new apigw.RestApi(this, `${props.devName}BookingApi`, { 
            // set up CORS            
            defaultCorsPreflightOptions: {
                allowHeaders: [
                    'Content-Type',
                    'X-Amz-Date',
                    'Authorization',
                    'X-Api-Key',
                    'X-Amz-Security-Token'
                  ],
                  statusCode: 200,
                  allowMethods: ['OPTIONS', 'GET', 'POST', 'DELETE'],
                  allowCredentials: true,
                  allowOrigins: Cors.ALL_ORIGINS           
            },
            deploy: true
        });

If I manually enable CORS in the AWS console I do not receive a CORS error from the frontend. The CORS options in the code are the same as the ones I put in manually. Also strange is, that eventhough I get the CORS error from the frontend, the WebSocket posts the output of the StepFunction.

I have read this but the solution does not work for me.

edit1: added Errormessage

like image 375
Tristan Müller Avatar asked Oct 24 '25 09:10

Tristan Müller


1 Answers

I have found the solution!

The setup was fine like this. I was missing this part in the apigw.AWSIntegration options:

integrationResponses: [
                    {
                      responseParameters: {
                        'method.response.header.Access-Control-Allow-Origin': "'*'",
                      },
                      responseTemplates: {
                        'application/json': JSON.stringify({
                          message: '$util.parseJson($input.body)',
                          state: 'ok',
                        }),
                      },
                      statusCode: '200',

and also

methodResponses: [{ 
            statusCode: '200',
            // important for CORS
            responseParameters: {
                'method.response.header.Content-Type': true,
                'method.response.header.Access-Control-Allow-Origin': true,
                'method.response.header.Access-Control-Allow-Credentials': true
            }
        }]

in .addMethod

edit1: This link helped me to find the solution

edit2: updated body of methodResponses:

like image 125
Tristan Müller Avatar answered Oct 27 '25 02:10

Tristan Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!