0
0
AwsDebug / FixBeginner · 4 min read

How to Fix API Gateway CORS Error Quickly and Easily

To fix a CORS error in AWS API Gateway, you must enable CORS by configuring the OPTIONS method with the correct headers like Access-Control-Allow-Origin. Also, ensure your API responses include these headers so browsers allow cross-origin requests.
🔍

Why This Happens

CORS errors occur because browsers block requests from one origin to another unless the server explicitly allows it. In AWS API Gateway, if you don't configure the OPTIONS method or fail to include the right headers in responses, the browser will block your API calls.

http
GET /resource
Response Headers:
  Content-Type: application/json

// Missing CORS headers like Access-Control-Allow-Origin
Output
Access to fetch at 'https://api.example.com/resource' from origin 'https://myapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
🔧

The Fix

Enable CORS in API Gateway by adding an OPTIONS method that returns the correct headers. Also, add Access-Control-Allow-Origin and other CORS headers to your actual API responses. This tells browsers your API allows requests from your web app's origin.

http
OPTIONS /resource
Response Headers:
  Access-Control-Allow-Origin: '*'
  Access-Control-Allow-Methods: 'GET,POST,OPTIONS'
  Access-Control-Allow-Headers: 'Content-Type'

GET /resource
Response Headers:
  Access-Control-Allow-Origin: '*'
  Content-Type: application/json
Output
Browser allows cross-origin requests without CORS errors.
🛡️

Prevention

Always configure CORS when creating new API Gateway endpoints. Use the AWS Console or Infrastructure as Code tools to automate adding OPTIONS methods and CORS headers. Test your API with browser tools to confirm headers are present before deploying.

Keep your CORS policy as strict as possible by specifying exact origins instead of using '*'. This improves security.

⚠️

Related Errors

  • Missing OPTIONS method: API Gateway returns 403 or 404 for preflight requests. Fix by adding OPTIONS method.
  • Incorrect headers: Missing or wrong Access-Control-Allow-Headers causes failures. Ensure headers match client requests.
  • Lambda proxy integration: Lambda must return CORS headers in its response for API Gateway to forward them.

Key Takeaways

Configure the OPTIONS method in API Gateway to handle CORS preflight requests.
Include Access-Control-Allow-Origin and related headers in all API responses.
Avoid using '*' for origins in production; specify allowed origins for better security.
Test CORS headers with browser developer tools before deploying.
When using Lambda proxy integration, ensure Lambda returns CORS headers.