0
votes

I've created a REST API that API Gateway will route to. Using Postman I can do a POST request to my API Gateway and everything works fine. I have a static Angular site hosted on S3 that has CloudFront in front of it. When trying to make that same POST request from Cloudfront to S3 I get the following:

Access to XMLHttpRequest at 'API Gateway URL' from origin 'Cloud Front URL' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I've enabled CORS in my API Gateway, I've added Whitelisting for ORIGIN in my Cloudfront. I've added CORS to my S3. I'm banging my head here trying to figure out where I'm going wrong.

S3 CORS Rules:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>300</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Thank you for any help.

1
How do you enable CORS on S3? <CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>*</AllowedMethod> </CORSRule> </CORSConfiguration>anhlc
@anhlc Please see edit.mint
seems you don't have issue with S3. What language do you use at the backend behind API gateway? For example nodejs will need to set all these headers: response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");anhlc
@anhlc I'm using a .Net Core Web API backend. The S3 Front End uses angular.mint
Read the error message carefully: "Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response." This indicates that your request is trying to send access-control-allow-origin, which does not make sense -- that is a response header, not a request header, and should not be sent with a request (nor proposed in pre-flight). Showing the front-end code that actually makes the POST request seems appropriate, here.Michael - sqlbot

1 Answers

0
votes

I ran into something similar after enabling Lambda integrations by proxy in API Gateway. I solved the issue by return the following headers from the Lambda function itself:

return {
    'statusCode': 200,
    'body': json.dumps(event['body']),
    'headers': {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': True
}

Note that this was for a Python Lambda function