johnykes
johnykes

Reputation: 1965

serverless framework AWS REST API Gateway - 403 CORS error

I'm trying to create a function with CORS enabled. The function works as expected using Postman (cors headers present), but I get CORS error when trying from a browser (no cors header).

const getTicket = async event => {
    var ticketNumber = Date.now();
    return {
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Methods': '*',
            'Access-Control-Allow-Origin': '*',
        },
        statusCode: 200,
        body: JSON.stringify({"ticketNumber": ticketNumber})
    };
};
functions:
  getTicket:
    handler: code/common/ticket.getTicket
    runtime: nodejs12.x
    events:
      - http:
          method: get
          path: getTicket
          cors: true
          authorizer: 
            arn: ${self:custom.auth0.authorizer_arn}

I also tried few more ways of writing the serverless.yaml file, but none of them worked, the only difference between them being the created methods in my API Gateway. Sometimes I got GET+OPTIONS methods, sometimes only GET, but never worked with CORS.

I get the error: "Access to XMLHttpRequest at 'https://...amazonaws.com/prod/getTicket' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Upvotes: 0

Views: 1477

Answers (1)

Gareth McCumskey
Gareth McCumskey

Reputation: 1540

What you are likely seeing is that the server is returning an error before it reaches your return statements. In other words, API Gateway is returning a 502 or 403 (as these are the most common errors), and those specific returns have no CORS headers present by default in API Gateway. I would recommend using CloudWatch to inspect the specific Lambda invocations to determine if your Lambda function itself is erroring out and correct that.

You can also force your API Gateway to return the CORS headers for all responses. In the resources section of the serverless.yml file you can do the following and add any additional entries for other status codes:

resources:

  Resources:

    GatewayResponseDefault4XX:

      Type: 'AWS::ApiGateway::GatewayResponse'

      Properties:

        ResponseParameters:

          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"

          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"

        ResponseType: DEFAULT_4XX

        RestApiId:

          Ref: 'ApiGatewayRestApi'

Upvotes: 3

Related Questions