Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS on Serverless yml

I have a React application and trying to access to serverless from aws. But I have below error

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.test.com' is therefore not allowed access. The response had HTTP status code 502.

End point url is https://key.execute-api.ap-southeast-2.amazonaws.com/dev/samplefunction

Setting on serverless.yml is

login:
    handler: login.login
    events:
      - http:
          path: login
          method: post
          cors:
            origin: 'https://admin.differentdomain.com'
            headers:
              - MY_CUSTOM_HEADER
              - Content-Type
              - X-Amz-Date
              - Authorization
              - X-Api-Key
              - X-Amz-Security-Token

Is there any other place I need to do CORS configuration?

like image 222
Lee Avatar asked Jun 08 '18 13:06

Lee


1 Answers

CORS setup in Serverless is explained in detail here: https://serverless.com/blog/cors-api-gateway-survival-guide/

In addition to the config in serverless.yml (which is for the preflight requests) you need to return the headers Access-Control-Allow-Origin and Access-Control-Allow-Credentials from your code. In your example and a Node.js implementation:

  return {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': 'https://admin.differentdomain.com',
      'Access-Control-Allow-Credentials': true,
    },
    body: {},
  };

Make sure to include the "https" part in the first header, I have stumbled over this previously.

like image 164
Ulli Avatar answered Oct 22 '22 15:10

Ulli