Search code examples
reactjsgoogle-chromeaws-lambdacorsheader

CORS issue React local client and AWS Lambda function


I'm trying to make a request from my localhost:3000 to a Lambda function that I developed

In my lambda function response I specified all needed headers to allow this

    return {
    'statusCode': 200,
    'body': json.dumps(result_object),
    'headers': {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',  # Use '*' for allowing any origin, or specify a domain to restrict access
        'Vary': 'Origin',
        'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',  # Optionally add other methods your API supports
        'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Access-Control-Allow-Origin,Access-Control-Allow-Methods',  # Optionally specify other headers your API accepts
    }
}

Also when I fetch the response say in Postman, I can see all the correct headers

enter image description here

But when I do the same via the react app from Chrome or Safari, I get these errors:

Access to fetch at ... from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What also can I do to fix this? Is there any issue in my headers format?


Solution

  • First thing "You have to enable CORS in both Lambda and API Gateway as well." If it doesn't work, then try adding domain name directly something like below.

    "Access-Control-Allow-Origin": "https://localhost:3000"
    

    Example:

        return {
        'statusCode': 200,
        'body': json.dumps(result_object),
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': 'https://localhost:3000',  # Use '*' for allowing any origin, or specify a domain to restrict access
            'Vary': 'Origin',
            'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',  # Optionally add other methods your API supports
            'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Access-Control-Allow-Origin,Access-Control-Allow-Methods',  # Optionally specify other headers your API accepts
        }
    }
    

    Please refer the below link for more details: Enabling CORS for a REST API resource