我不确定这是否是一个错误,或者我是否做错了什么,但当我尝试将自定义域附加到我的 API 网关时,我不断收到此异常:
下午 3:28:13 |创建失败 | AWS::ApiGatewayV2::ApiMapping
| API/Default...DomainName$default 资源处理程序返回消息: “指定的域名标识符无效(服务: 亚马逊ApiGatewayV2;状态代码:404;错误代码:NotFoundException; 请求 ID:;代理:空)”(RequestToken:, HandlerErrorCode:GeneralServiceException)
这是我的代码:
export class APIStack extends Stack {
constructor(scope: Construct, id: string, props: APIStackProps) {
super(scope, id, props);
// Custom Domain
const apiDomainName = `api.${props.appName}.${props.rootDomain}`;
const hostedZone = HostedZone.fromLookup(this, "HostedZone", {
domainName: props.rootDomain,
});
const domainCertificate = new Certificate(
this,
`${props.appName}-Certificate`,
{
domainName: apiDomainName,
certificateName: `${props.appName}-Certificate`,
validation: CertificateValidation.fromDns(hostedZone),
}
);
// Custom domain for API
const gatewayDomain = new DomainName(this, `${props.appName}-DomainName`, {
domainName: apiDomainName,
certificate: domainCertificate,
endpointType: EndpointType.REGIONAL,
});
// Security
const apiAuthorizer = new HttpUserPoolAuthorizer(
`${props.appName}-APIAuthorizer`,
props.userPool,
{ userPoolClients: [props.appClient] }
);
// API
const httpApi = new HttpApi(this, `${props.appName}-API`, {
defaultAuthorizer: apiAuthorizer,
defaultDomainMapping: {
domainName: gatewayDomain,
mappingKey: "$default",
},
});
new ApiMapping(this, "Mapping", {
domainName: gatewayDomain,
api: httpApi,
});
// route53 records
new ARecord(this, `${props.appName}-AliasRecord`, {
zone: hostedZone,
recordName: apiDomainName,
target: RecordTarget.fromAlias(
new ApiGatewayv2DomainProperties(
gatewayDomain.regionalDomainName,
gatewayDomain.regionalHostedZoneId
)
),
});
// Lambdas
const testLambda = new NodejsFunction(this, `${props.appName}-TestLambda`, {
runtime: Runtime.NODEJS_20_X,
handler: "handler",
functionName: `${props.appName}-test-function`,
entry: path.join(__dirname, "../lambdas/endpoints/test", "index.ts"),
});
// Registering routes
const testLambdaIntegration = new HttpLambdaIntegration(
"TestLambdaIntegration",
testLambda
);
httpApi.addRoutes({
path: "/test",
methods: [HttpMethod.GET],
integration: testLambdaIntegration,
authorizer: apiAuthorizer,
});
}
}
当我创建 ApiMapping 时发生错误,据我所知,CloudFormation 正在尝试在创建和传播 API 网关 (gatewayDomain) 的域之前创建映射。我尝试在创建映射之前显式添加依赖项来创建域,但它仍然不起作用:
apiMapping.node.addDependency(gatewayDomain)
我发现使用控制台或使用 aws cli 创建映射是可行的,但我想使用 cdk 来实现此目的。任何帮助将不胜感激:)
指定
defaultDomainMapping
会创建 ApiMapping
资源 - 您不必自己创建它。
您看到的错误可能是由于无效的映射键
$default
- 看起来您只想将域的根用于您的 API - 只需将 mappingKey
属性留空即可。