How to integrate AWS API Gateway API Key with Axios | CORS Error

Viewed 497

I have built an API in AWS API Gateway. I have written the endpoints to perform basic CRUD operations as well. I am making a call to those endpoints using axios from my React frontend. The APIs in turn call AWS Lambda functions to interact with DynamoDB.

Since DynamoDB contains sensitive user data, I wish to secure it with an API key.

As per the steps mentioned here and here.

Now in order to make an API call I had the following code. Please note that I have swapped in the real values with dummy values for explanation purposes.

src/config/api.js

const customHeaders = {
  "X-Api-Key": "thisIsADummyStringForExplanation",
  "Content-Type": "application/json",
};

const axiosInstance = axios.create({
  baseURL: "https://this.is.a.dummy.base.url/v0",
  headers: customHeaders,
});

const Aws_Api_Gateway_GET = (uri) => {
  return axiosInstance({
    method: "get",
    url: `${uri}`,
    timeout: 2000,
  });
};

export { Aws_Api_Gateway_GET };

Following is the Code that I wrote in order to make a GET request at the API endpoint

Aws_Api_Gateway_GET("/my-resource")
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.error(err);
  });

THE ISSUE

This code throws CORS Error. I can assure that I have enabled CORS on the API Gateway by selecting the Enable CORS option for each and every resource.

enter image description here

Following is the error

Access to XMLHttpRequest at 'https://this.is.a.dummy.base.url/v0/my-resource' from origin 'http://localhost:3000' 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.

But when I try the same using Postman, it works.

enter image description here

Can someone please help me get rid of the CORS Error ?

Thanks in advance.

0 Answers
Related