Skip to content

Blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

0

Error: Access to fetch at 'https://myapicode.execute-api.us-east-2.amazonaws.com/dev' from origin 'http://mywebsite' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I have a REST API with method POST. I have set up Enable CORS with allowing following:

  • Default 4 and Default 5 for Gateway Response option,
  • OPTIONS and POST for Access-Control-Allow-Methods,
  • Content-Type for Access-Control-Allow-Headers
  • '*' with Access-Control-Allow-Origin

This API is connected to Lambda function. I have put 'API Key required' to false (I tried solving this issue with 'true' and setting up api key with usage plan and adding it in my request but it didn't work). I have also given trigger access of Lambda to my API. My return block for lambda_handler looks like:

return {
        'statusCode': 200,
        'headers': {
            "Access-Control-Allow-Origin": "*",
        },
        'body': json.dumps({'rows': rows_as_dict})
    }

I am not using AWS service to host the web app, I have a private domain. I am calling the API in my React app as follows:

fetch(apiUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payLoad),
    })
      .then(function (response) {
        if (!response.ok) {
          throw new Error("HTTP error! Status: " + response.status);
        }
        return response.json();
      })
      .then(function (parsedResponse) {
        const responseBody = JSON.parse(parsedResponse.body);
        const updatedList = responseBody.rows.map(function (row) {
          return {
            value: row.PLACEKEY,
            label: `${row.LOCATION_NAME}, ${row.STREET_ADDRESS}, ${row.CITY}, ${row.REGION}, ${row.POSTAL_CODE}`,
          };
        });
        setOptions((prevList) => [...prevList, ...updatedList]);
        console.log("Updated List:", updatedList);
      })
      .catch(function (error) {
        console.error("Error posting data to API:", error);
      });
  }

I have been trying to solve this error for past 24 hours and nothing worked, it only made me cry several times. PLEASE HELP ME

1 Answer
1

I understand your frustration with this CORS issue. It's a common problem that can be tricky to resolve. Based on the information you've provided, there are a few areas we can focus on to troubleshoot and potentially resolve the issue:

  1. API Gateway Configuration: Your CORS configuration in API Gateway seems mostly correct, but there are a couple of things to double-check:

    • Ensure that you've enabled CORS for both the OPTIONS and POST methods.
    • Make sure you've deployed your API after making CORS changes.
    • Verify that the 'Access-Control-Allow-Headers' includes all necessary headers, not just 'Content-Type'. You might want to add 'Authorization' and others if needed.
  2. Lambda Function: Your Lambda function is returning CORS headers, which is good. However, you might want to include additional headers:

    return {
        'statusCode': 200,
        'headers': {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token",
            "Access-Control-Allow-Methods": "OPTIONS,POST"
        },
        'body': json.dumps({'rows': rows_as_dict})
    }
  3. OPTIONS Method: Ensure that you have an OPTIONS method set up in your API Gateway that responds successfully to preflight requests. This method should return a 200 status code with the appropriate CORS headers.

  4. API Gateway Method Response: Check your API Gateway's Method Response for both OPTIONS and POST methods. Ensure that you've added the necessary CORS headers there as well.

  5. Integration Response: In the Integration Response section of your API Gateway, make sure you've mapped the CORS headers from your Lambda function to the actual response.

  6. Client-side Request: Your fetch request looks fine, but you might want to try adding the 'mode' option to explicitly state that you're making a CORS request:

    fetch(apiUrl, {
      method: "POST",
      mode: 'cors',
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payLoad),
    })
  7. API Deployment: After making any changes in API Gateway, remember to deploy your API again.

If you've checked all these areas and are still experiencing issues, you may want to use the browser's developer tools to inspect the actual requests being sent and the responses received. This can provide more detailed information about what's going wrong.

Remember, CORS errors are often related to server-side configuration rather than client-side code. If the problem persists, you might need to review your API Gateway and Lambda configurations in detail, possibly with AWS support if needed.
Sources
CORS Access-Control-Allow-Origin Header missing - Api Gateway HTTP / EC2 | AWS re:Post
API Gateway CORS Error | AWS re:Post
Cors policy with cloudfront + Api Gateway (VPC Links) | AWS re:Post
Requests to API Gateway fail with CORS error if I add headers. | AWS re:Post

answered a year ago
EXPERT
reviewed a year ago

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.