我正在尝试使用 AWS CDK 构建应用程序,如果我要使用 AWS 控制台手动构建应用程序,我通常会在 API 网关中启用 CORS。
即使我可以将 swagger 从 API Gateway 导出并找到许多选项来为 OPTIONS 方法生成 Mock 端点,但我不知道如何使用 CDK 执行此操作。目前我正在尝试:
const apigw = require('@aws-cdk/aws-apigateway');
在哪里:
var api = new apigw.RestApi(this, 'testApi');
并定义 OPTIONS 方法,例如:
const testResource = api.root.addResource('testresource');
var mock = new apigw.MockIntegration({
type: "Mock",
methodResponses: [
{
statusCode: "200",
responseParameters : {
"Access-Control-Allow-Headers" : "string",
"Access-Control-Allow-Methods" : "string",
"Access-Control-Allow-Origin" : "string"
}
}
],
integrationResponses: [
{
statusCode: "200",
responseParameters: {
"Access-Control-Allow-Headers" : "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
"Access-Control-Allow-Origin" : "'*'",
"Access-Control-Allow-Methods" : "'GET,POST,OPTIONS'"
}
}
],
requestTemplates: {
"application/json": "{\"statusCode\": 200}"
}
});
testResource.addMethod('OPTIONS', mock);
但这不会部署。当我运行“cdk deploy”时,我从 cloudformation 堆栈部署中得到的错误消息是:
Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: Access-Control-Allow-Origin] (Service: AmazonApiGateway; Status Code: 400; Error Code: BadRequestException;
想法?