DEV Community

Discussion on: How to fix AWS Lambda & API Gateway cors Error

Collapse
 
mykezero profile image
Mykezero

Sounds like you're missing something on the API Gateway side of things.

You'll need two API Methods for the CORS: OPTIONS and POST.

Options Method

For OPTIONS, you'll want to make sure that the Method Response section contains the following headers:

  • Access-Control-Allow-Headers
  • Access-Control-Allow-Methods
  • Access-Control-Allow-Origin

Image description

Next, you'll want to configure the Integration Response section for the OPTIONS method, to include the values

  • Access-Control-Allow-Headers: 'Content-Type'
  • Access-Control-Allow-Methods: 'OPTIONS,POST'
  • Access-Control-Allow-Origin: '*'

Image description

Post Method

For POST, you'll want to make sure that the Method Response section contains the following headers:

  • Access-Control-Allow-Origin

Image description

Next, you'll want to configure the Integration Response section for the POST method, to include the values:

  • Access-Control-Allow-Origin: '*'

Image description

With that in place, you should be able to call API gateway using Axios by doing the following:

import axios from "axios";

(async () => {
  const result = await axios.post("https://3xqqgy12ga.execute-api.us-east-1.amazonaws.com/Test/testwithcorsenabled", null, {
    headers: {
      "Content-Type": "application/json"
    }
  });
  console.log(result);
})().catch(e => {
});
Enter fullscreen mode Exit fullscreen mode

Notice that 'Content-Type' was one of the allowed headers in the OPTIONS Integration Response section.

On success, the browser dev tools should show an OPTIONS request being fired and then a POST right after:

Image description

My approach would be to spin up a test API Gateway, decide what headers you'll need back and incrementally add / test them using Axios for the POST.

Hopefully this helps a little bit ^^

Collapse
 
jacksonkasi profile image
Jackson Kasi • Edited

Really thanks for spending your time to help me. Its now work :)