I am struggling with the CORS error.
- I’ve deployed a backend using APIGATEWAY. It works properly via POSTMAN at the https://APIGATEWAY_URL
- I’ve deployed a web app using CLOUDFRONT, and it works too, if I open the https://CLOUDFRONT_URL from the browser.
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
2
Answers
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
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 theOPTIONS
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
andAccess-Control-Allow-Headers
headers for all other requests of different types includingGET
,PUT
,POST
andDELETE
exceptOPTIONS
(since OPTIONS is already handled by the API Gateway).For me, it was a .NET Lambda function, so I did something like this.
You can find more details here – Enabling CORS for a REST API resource