CORS not working with AWS SAM

0

Hi everyone,

I setup CORS using SAM a few weeks ago and it was working fine until I today. Now, I keep getting Access to XMLHttpRequest at 'abc' from origin 'xyz' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have this in my template.yaml file:

Globals:
  Api:
    Cors:
      AllowMethods: "'GET,POST,OPTIONS'"
      AllowHeaders: "'Content-Type'"
      AllowOrigin: "'*'"

and in my lambda function, I'm returning the the headers like so:

return {
        "statusCode": 200,
        'headers': {
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,GET'
        },
        "body": json.dumps(
            {
                "message": response,
            }
        ),
    }

but I'm still getting Access to XMLHttpRequest at 'abc' from origin 'xyz' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. any time I try to hit that API from the frontend.

I also tried manually enabling CORS from the API Gateway, but it threw unspecified errors. Enter image description here

From reading other support posts, I thought maybe adding a 200 method response on the gateway would fix it, but that didn't change anything either, even after adding a model for the response with an accurate schema.

I didn't change anything with the headers so I don't know why it stopped working. I also tried clearing my cache and running from an incognito window to make sure my browser cache wasn't messing with anything. Any help would be much appreciated.

Edit: I forgot to mention, this API works fine when I run it locally using sam local start-api. It only throws this error when it is deployed.

2 Answers
0
Accepted Answer

I finally figured out a solution. The problem popped up after adding multithreading to my Python code. There weren't any errors with it, it wasn't returning anything without closing all threads first, and it worked locally, but removing multithreading removed the CORS error. It's a little slower now, but it's working again. Disappointing to know AWS Lambda doesn't support multithreading, but at least it's working again.

zah
answered 8 months ago
0

Are you missing POST from this? Access-Control-Allow-Methods': 'OPTIONS,GET'

profile picture
EXPERT
answered 8 months ago
  • I am not. This lambda is only used for GET. I did try adding POST, but that didn't change anything

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions