Javascript 使用CDK在API网关方法响应中指定内容类型
我正在使用CDK创建到非公共S3存储桶的代理API网关。 S3存储桶包含html、javascript和css文件 我使用CDK创建了一个api,如下所示:Javascript 使用CDK在API网关方法响应中指定内容类型,javascript,amazon-s3,aws-api-gateway,aws-cdk,Javascript,Amazon S3,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', integrationHttpMet
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/html
到text/css
,application/javascript
不等,具体取决于文件
如何设置此API,通过将集成响应的相同内容类型头值传递给方法响应,在每个文件上返回正确的内容类型?如果我能从S3传递内容类型头,那就最好了,因为它已经正确返回了。CDK文档不是很好。我设法找到了一个解决办法: 我必须在
integrationResponses
中添加responseParameters
,以将内容类型
标题从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'
}]
})