- Newest
- Most votes
- Most comments
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:
-
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.
-
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}) } -
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.
-
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.
-
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.
-
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), }) -
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
Relevant content
- asked 2 years ago
- asked 9 months ago
- asked 2 years ago
- AWS OFFICIALUpdated a month ago
