当使用AWS CDK构建包含API Gateway的堆栈时,可能会遇到指定API Gateway处理程序时出现困难的情况。 这是由于CDK对于API Gateway有一些约束(如必须有至少一个IntegrationResponse)。 以下是一个示例,其中最初出现了这个问题:
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'MyApi'
});
api.root.addMethod('GET', new LambdaIntegration(handler))
在这个示例中,由于缺少IntegrationResponse,API Gateway处理程序将无法正确指定。 要解决这个问题,可以添加一个空的IntegrationResponse,如下所示:
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'MyApi'
});
api.root.addMethod('GET', new LambdaIntegration(handler), {
methodResponses: [
{
statusCode: "200",
responseModels: {
"application/json": new apigateway.EmptyModel()
}
}
]
})
通过添加一个空的IntegrationResponse,问题得到解决,API Gateway的处理程序将被正确指定。