How to Fix API Gateway CORS Error Quickly and Easily
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.
GET /resource
Response Headers:
Content-Type: application/json
// Missing CORS headers like Access-Control-Allow-OriginThe 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.
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
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-Headerscauses failures. Ensure headers match client requests. - Lambda proxy integration: Lambda must return CORS headers in its response for API Gateway to forward them.