簡體   English   中英

使用 CDK 在 API 網關方法響應中指定 content-type

[英]Specify content-type in API Gateway method response using 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'
    }]
  })

它工作正常,但有一個問題。 響應的內容類型始終設置為application/json 我可以看到集成響應的內容類型(來自 S3 的響應)從text/htmltext/cssapplication/javascript取決於文件。

如何通過將集成響應的相同內容類型 header 值傳遞給方法響應來設置此 API 以在每個文件上返回正確的內容類型? 如果我可以從 S3 傳遞內容類型 header 最好,因為它已經正確返回。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM