【问题标题】:Typescript - AWS CDK Enable CORSTypescript - AWS CDK 启用 CORS
【发布时间】:2021-10-14 19:04:20
【问题描述】:

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

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

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

我已经像这样设置了我的 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
        });

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

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

edit1:添加错误消息

【问题讨论】:

    标签: typescript amazon-web-services cors aws-api-gateway aws-cdk


    【解决方案1】:

    我找到了解决办法!

    这样的设置很好。我在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',
    

    还有

    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
                }
            }]
    

    .addMethod

    edit1:这个link帮助我找到了解决方案

    edit2:methodResponses 的更新正文:

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 2019-03-16
      • 1970-01-01
      • 2021-10-03
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2018-10-03
      相关资源
      最近更新 更多