Ollie
Ollie

Reputation: 141

API Gateway CORS 204 error with CORS enabled in API Gateway and 'Access-Control-Allow-Origin: *' in lambda header

I have an API Gateway (HTTP) > Lambda > DynamoDB set up. I can successfully do a PUT and GET request through Postman but I am receiving a CORS error when I try and do a PUT request through my browser. I can successfully do a GET request through the browser.

A Post request through the browser returns

Access to XMLHttpRequest at 'https://xxx.execute-api.eu-west-1.amazonaws.com/items' from origin 'http://localhost:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have enabled CORS on the API Gateway. Automatic redeploy is on. I have also redeployed manually just in case.

enter image description here

I have also added `Access-Control-Allow-Origin' and 'Access-Control-Allow-Methods' to the headers in the lambda response. I have tried the lambda with and without these responses as I understand API Gateway should resolve the pre-flight request. Both ways still return a CORS 204 error.

enter image description here


const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event, context) => {
  let body;
  let statusCode = 200;
  const headers = {
    "Content-Type": "application/json",
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'OPTIONS,PUT,GET'
  };

  try {
    switch (event.routeKey) {
      case "GET /items":
        // database call
      case "PUT /items":
        // databse put
      default:
        throw new Error(`Unsupported route: "${event.routeKey}"`);
    }
  } catch (err) {
    statusCode = 400;
    body = err.message;
  } finally {
    body = JSON.stringify(body);
  }

  return {
    statusCode,
    body,
    headers
  };
};

I believe I should be seeing my headers in Postman, but I am not. I know the API Gateway is updating because if I remove Access-Control-Allow-Origin in the API Gateway Console, my GET request also fails due to CORS.

enter image description here

Upvotes: 0

Views: 2477

Answers (1)

Ollie
Ollie

Reputation: 141

I found the solution here: aws apigateway not returning expected preflight headers, CORS

The solution was to not use API Gateway for CORS since it was simply not working. I had to add an OPTIONS route and return the desired headers.

Frustrating since AWS docs say the following.

If you configure CORS for an API, API Gateway automatically sends a response to preflight OPTIONS requests, even if there isn't an OPTIONS route configured for your API. For a CORS request, API Gateway adds the configured CORS headers to the response from an integration.

Upvotes: 1

Related Questions