milan10k
milan10k

Reputation: 71

AWS API Gateway cors error when sending request from React app

I'm trying to send a GET request with headers from React app to the API Gateway endpoint which returns a pre-sign URL and I'm getting a cors error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here is my OpenAPI template for the OPTIONS method:

options:
  tags:
    - subject
  summary: subject data CORS
  security: []
  responses:
    "200":
      description: OK
      headers:
        Access-Control-Allow-Credentials:
          schema:
            type: string
        Access-Control-Allow-Origin:
          schema:
            type: string
        Access-Control-Allow-Methods:
          schema:
            type: string
        Access-Control-Allow-Headers:
          schema:
            type: string
  x-amazon-apigateway-integration:
    responses:
      default:
        statusCode: "200"
        responseParameters:
          method.response.header.Access-Control-Allow-Credentials: "'false'"
          method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,FileName,Username'"
          method.response.header.Access-Control-Allow-Methods: "'*'"
          method.response.header.Access-Control-Allow-Origin: "'*'"
        responseTemplates:
          application/json: |
            {}
    passthroughBehavior: when_no_match
    requestTemplates:
      application/json: '{"statusCode": 200}'
    type: mock

and here is the response from my Lambda function:

const response = {
  statusCode: statusCode,
  headers: {
    'Access-Control-Allow-Headers':
      'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,FileName,Username',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*'
  },
  body: JSON.stringify(body)
};

return response;

When sending request without headers, it is working. Also, with Postman I don't have any problems in both cases.

What am I missing here? I really appreciate any help you can provide.

Upvotes: 0

Views: 2473

Answers (1)

milan10k
milan10k

Reputation: 71

I managed to solve this issue. The problem was in API Gateway settings under Binary Media Types, for me it was set to "/" then I just removed that binary media type and it worked. If someone is getting a preflight CORS error with status code 500 - this might be the issue.

Upvotes: 1

Related Questions