【发布时间】:2021-09-15 19:41:29
【问题描述】:
我正在尝试使用 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 + Lambda + DynamoDB + SQS + SES + ...... all 的 excellent 示例i> 使用 CDK 管理:github.com/davidtucker/ps-serverless-app
-
您应该使用
RestApi(具有更多功能)而不是RestApiBase(基类)。前者支持CORS配置,后者不支持。
标签: typescript amazon-web-services aws-lambda aws-cdk api-gateway