2

im creating a serverless api with nodejs and im using api gateway to invoke my lambda functions and i have my frontend build with reactjs. when i call my api through react app i get following error.

Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*,http://localhost:9988', but only one is allowed

here is my serverless.yaml

  listBank:
    handler: bank/list.list
    events:
      - http:
          path: bank
          method: get
          cors:
            origins:
              - '*'
              - 'http://localhost:9988'
            headers:
              - Content-Type
              - X-Api-Key
              - Access-Control-Allow-Headers
              - Access-Control-Allow-Origin
              - Access-Control-Allow-Methods
              - Access-Control-Allow-Credentials
            allowCredentials: false
          private: true

here is my get function respond header

const response = {
  statusCode: 200,
  headers: {
    "Access-Control-Allow-Origin" : "*", 
    "Access-Control-Allow-Credentials" : true 
  },
  body: JSON.stringify(result.Items),
};

what i am missing?

Jack
  • 1,162
  • 3
  • 12
  • 27
  • did you check if its actually enabled in API Gateway console? You gotta see OPTIONS under your resource name and `mock` as integration request in it. – Can Sahin Oct 21 '18 at 07:12

1 Answers1

0

Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*,http://localhost:9988', but only one is allowed

The Access-Control-Allow-Origin header can only have one value, while yours has two.

The CORS part of your serverless config specifies two.

cors:
  origins:
    - '*'
    - 'http://localhost:9988'

Note that this serverless is for preflight requests as per the docs (https://www.serverless.com/blog/cors-api-gateway-survival-guide/).

While the preflight request only applies to some cross-origin requests, the CORS response headers must be present in every cross-origin request. This means you must add the Access-Control-Allow-Origin header to your responses in your handlers.

So if you'd like to add multiple origins, you'd have to do it in your handler, defining the allowed origins and making the handler return the correct one based on the request origin. Example available in this answer.

Dostrelith
  • 922
  • 5
  • 13