'Enabling cors in serverless?
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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Damjan Ostrelic |
