使用 CDK 在 API 网关方法响应中指定 content-type

Specify content-type in API Gateway method response using CDK

我正在使用 CDK 创建到 non-public 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'
    }]
  })

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

如何通过将集成响应的相同内容类型 header 值传递给方法响应,将每个文件的 API 设置为 return 正确的内容类型?最好是我可以从 S3 传递 content-type header,因为它已经 return 正确。

CDK 文档不是很好。我设法找到了解决方案: 我必须在 integrationResponses 中添加 responseParameters 以将 Content-Type header 从 S3 设置为 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'
      }]
    })