Reputation: 105
I am trying to enable Cors for AWS API Gateway using cdk and I seem to be doing everything correctly but the react front end still gives cors error. My cdk code looks like this. Pasting the same url in the chrome browser works. I am using AWS version 1.90 for lambda , api gateway etc and cannot upgrade.
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,
},
},
],
},
}
);
It does not work. Normal postman calls work and pasting the url in the browser works but React gives cors error.
Manually enabling cors gives the following error:
Upvotes: 0
Views: 2798
Reputation:
Since you are using API Gateway v1 REST APIs, take a look at the CORS documentation and examples for API Gateway v1 REST APIs.
To enable CORS for your REST API, you must first use RestApiBase
instead of RestApi
, and then add the following configuration to the RestApi
(along with apiSubDomain
, etc.)
defaultCorsPreflightOptions: {
allowOrigins: apigateway.Cors.ALL_ORIGINS,
allowMethods: apigateway.Cors.ALL_METHODS
}
Upvotes: 1