Typescript - AWS CDK 启用 CORS

Tri*_*ler 4 amazon-web-services cors typescript aws-api-gateway aws-cdk

我的 cdk 项目的一部分是一个 Websocket,它获取由请求触发的 StepFunction 的输出POST。整个工作流程就像邮递员一样在 aws 控制台中运行。

但如果我在前端尝试它,我会收到 CORS 错误:

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

我已经像这样设置了 CORS 选项:

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
        });
Run Code Online (Sandbox Code Playgroud)

如果我在 AWS 控制台中手动启用 CORS,我不会从前端收到 CORS 错误。代码中的CORS选项与我手动输入的相同。同样奇怪的是,即使我从前端收到 CORS 错误,WebSocket 也会发布 StepFunction 的输出。

我已阅读此内容,但该解决方案对我不起作用。

edit1:添加错误消息

Tri*_*ler 5

我已经找到解决方案了!

像这样的设置就很好。我在选项中遗漏了这部分apigw.AWSIntegration

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

并且

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
            }
        }]
Run Code Online (Sandbox Code Playgroud)

.addMethod

edit1:此链接帮助我找到了解决方案

edit2:更新的正文methodResponses