skip to Main Content

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


  1. 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.

    enter image description here

    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

    Login or Signup to reply.
  2. 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.

    1. 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:

      • Access-Control-Allow-Methods
      • Access-Control-Allow-Headers
      • Access-Control-Allow-Origin

      And this is how, I did it for one of my applications.

      enter image description here

    2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search