Reputation: 21
I am struggling with the CORS error.
PROBLEM
The web app requests are blocked because of the CORS Problem. Access to XMLHttpRequest at '[APIGATEWAY_URL]' from origin ' [CLOUDFRONT_URL]' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Am I missing some configurations?
Thanks for help
Upvotes: 0
Views: 1347
Reputation: 7069
For me, I had to do 2 things in order to fix this CORS issue. I was using Amazon API Gateway REST API with Lambda using Proxy integration.
First, you need to configure your API Gateway resource to implement an OPTIONS
method that can respond to the OPTIONS
preflight request with at least the following response headers mandated by the Fetch standard:
And this is how, I did it for one of my applications.
Second thing, if you are doing the proxy integration, then your backend is also responsible for returning the Access-Control-Allow-Origin
and Access-Control-Allow-Headers
headers for all other requests of different types including GET
, PUT
, POST
and DELETE
except OPTIONS
(since OPTIONS is already handled by the API Gateway).
For me, it was a .NET Lambda function, so I did something like this.
builder.Services.AddCors(item =>
{
item.AddPolicy("CORSPolicy", builder =>
{
builder.WithOrigins("https://abcd.cloudfront.net")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
You can find more details here - Enabling CORS for a REST API resource
Upvotes: 1
Reputation: 10734
Take a look at the CDK Script for the AWS example PAM application. This app successfully invokes an API Gateway endpoints using a React app that uses Cloud Front. This app demonstrates how to succesfully set up this configuration.
Backend is here:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files
CDK/Front end is here:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk/photo_asset_manager
Upvotes: 0