typescript - AWS CDK API Gateway 启用 Cors
问题描述
我正在尝试使用 cdk 为 AWS API Gateway 启用 Cors,我似乎做的一切都是正确的,但反应前端仍然给出 cors 错误。我的 cdk 代码如下所示。在 chrome 浏览器中粘贴相同的 url 是可行的。我正在为 lambda 、 api gateway 等使用 AWS 1.90 版,无法升级。
var apiBase = new RestApiBase(this, `my-${this.resourcePrefix}-api`, {
apiSubDomain: `${this.appName}`,
stage: this.stage,
});
const corsOptions = {
allowOrigins: Cors.ALL_ORIGINS,
allowHeaders: Cors.DEFAULT_HEADERS,
allowMethods: Cors.ALL_METHODS,
};
// create a lambda function in the VPC with SQL Server access
const sqlConstruct = new VpcSqlLambda(this, "my-api-lambda", {
resourceSlashPrefix: this.resourceSlashPrefix,
dbServerParamValue: process.env.DBSERVER ?? "xx.xx.xx.xx",
dbNameParamValue: process.env.DBSERVER ?? "mydbname",
dbUsernameParamValue: process.env.DBSERVER ?? "user",
});
apiBase.AddLambdaIntegration(
sqlConstruct.lambda,
{
resource: "getList",
method: "GET",
options: {
defaultCorsPreflightOptions: corsOptions,
integrationResponses: [
{
statusCode: "200",
responseParameters: {
"method.response.header.Access-Control-Allow-Headers":
"'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
"method.response.header.Access-Control-Allow-Origin": "'*'",
"method.response.header.Access-Control-Allow-Credentials":
"'false'",
"method.response.header.Access-Control-Allow-Methods":
"'OPTIONS,GET,PUT,POST'",
"method.response.body.Content-Type": "'application/json'",
"method.response.body.Models": "'Empty'",
},
},
],
passthroughBehavior: apigw.PassthroughBehavior.NEVER,
requestTemplates: {
"application/json": '{"statusCode": 200}',
},
methodResponses: [
{
statusCode: "200",
responseParameters: {
"method.response.header.Access-Control-Allow-Headers": true,
"method.response.header.Access-Control-Allow-Methods": true,
"method.response.header.Access-Control-Allow-Credentials": true,
"method.response.header.Access-Control-Allow-Origin": true,
},
},
],
},
}
);
这没用。普通邮递员调用工作并将 url 粘贴到浏览器中工作,但 React 给出了 cors 错误。
手动启用 cors 会出现以下错误:
解决方案
由于您使用的是 API Gateway v1 REST API,因此请查看 API Gateway v1 REST API 的CORS 文档和示例。
要为您的 REST API 启用 CORS,您必须首先使用RestApiBase
而不是RestApi
,然后将以下配置添加到RestApi
(以及apiSubDomain
等)
defaultCorsPreflightOptions: {
allowOrigins: apigateway.Cors.ALL_ORIGINS,
allowMethods: apigateway.Cors.ALL_METHODS
}
推荐阅读
- autodesk-forge - 在查看器上选择 PDF 文本
- android - Android特性.getValue空数组
- php - 未找到接口 Matcher\RequestMatcherInterface'
- ios - 未找到匹配代码或已被使用
- ruby-on-rails - 我可以运行我的 rake 作业吗:在运行我的 rails 服务器时在同一个 docker 容器中工作?
- javascript - 切换新的 li 仍然计算最后一个
- c++ - 在 GUI 应用程序中使用线程
- python - pandas 中的平均值和虚拟值
- function - 如何正确地将 Win32 类对象传递给函数
- firebase - 添加 Firestore 依赖项会导致 Flutter 应用程序出错