使用 CDK 在 API Gateway 方法响应中指定内容类型

nta*_*lbs 4 javascript amazon-s3 amazon-web-services aws-api-gateway aws-cdk

我正在使用 CDK 创建到非公共 S3 存储桶的代理 API 网关。S3 存储桶包含 html、javascript 和 css 文件。

我使用 CDK 创建了一个 api,如下所示:

const api = new apigw.RestApi(this, 'Test-Web')

api.root
  .addResource('{file}')
  .addMethod('GET', new apigw.AwsIntegration({
    service: 's3',
    integrationHttpMethod: 'GET',
    path: `${bucket.bucketName}/{file}`,
    options: {
      credentialsRole: role,
      requestParameters: {
        'integration.request.path.file': 'method.request.path.file'
      },
      integrationResponses: [{
        statusCode: '200'
      }]
    }
  }), {
    requestParameters: {
      'method.request.path.file': true
    },
    methodResponses: [{
      statusCode: '200'
    }]
  })
Run Code Online (Sandbox Code Playgroud)

它工作正常,但有一个问题。响应的内容类型始终设置为application/json。我可以看到集成响应(来自 S3 的响应)的内容类型从text/html到变化text/cssapplication/javascript具体取决于文件。

如何通过将集成响应的相同内容类型标头值传递给方法响应来设置此 API 以在每个文件上返回正确的内容类型?如果我可以从 S3 传递内容类型标头,那就最好了,因为它已经正确返回。

nta*_*lbs 7

CDK 文档不是很好。我设法找到了一个解决方案:我必须添加responseParameters设置integrationResponsesContent-TypeS3 到 API 网关响应的标头。请看下面,特别是标有 的那一行<<<--

api.root
  .addResource('{file}')
  .addMethod(
    'GET',
    new apigw.AwsIntegration({
      service: 's3',
      integrationHttpMethod: 'GET',
      path: `${bucket.bucketName}/{file}`,
      options: {
        credentialsRole: role,
        requestParameters: {
          'integration.request.path.file': 'method.request.path.file'
        },
        integrationResponses: [{
          statusCode: '200',
          selectionPattern: '2..',
          responseParameters: {
            'method.response.header.Content-Type': 'integration.response.header.Content-Type' // <<<--
          },
        }, {
          statusCode: '403',
          selectionPattern: '4..'
        }]
      }
    }), {
      requestParameters: {
        'method.request.path.file': true
      },
      methodResponses: [{
        statusCode: '200',
        responseParameters: {
          'method.response.header.Content-Type': true // <<<-- 
        }
      }, {
        statusCode: '404'
      }]
    })
Run Code Online (Sandbox Code Playgroud)