EL-Mehdi Loukach
EL-Mehdi Loukach

Reputation: 772

React.js - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. [AWS - Lambda - API GATEWAY]

I have a react client application that sends form data to AWS API Gateway. When I test the API with Postman everything works fine, but when I use Axios in react, an error is shown in the console :

Access to XMLHttpRequest at 'https://execute-api.eu-west-3.amazonaws.com' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I enabled CORS in API Gateway methods, also my AWS Lambda function has Lambda proxy integration, but apparently it didn't solve the issue.

How can i fix this ? Thanks in advance.

----- UPDATE -------

Based on the comments, here is the build function for the response I'm sending from the Lambda function :

const buildResponse = (statusCode, body) => {
return {
    statusCode : statusCode,
    headers : {
        "Content-Type" : "application/json",
        "Access-Control-Allow-Headers" : "Content-Type",
        "Access-Control-Allow-Origin": "*",
    },
    body : JSON.stringify(body)
}
}

Where I make the call :

const get = async () => {
const params = {
  TableName: dynamoTable
}
const all= await scanDynamoRecords(params, []);
const body = {
  data: all
}
return buildResponse(200, body);
}

Upvotes: 5

Views: 18195

Answers (2)

LastryCoding
LastryCoding

Reputation: 126

Try to enable credentiels for axios like this:

axios.defaults.withCredentials = true;

Upvotes: 1

EL-Mehdi Loukach
EL-Mehdi Loukach

Reputation: 772

After reading about CORS and consulting with a professional, response headers must be updated to the following in order to fix the problem :

headers : {
        "Access-Control-Allow-Headers": "*",
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "*"      
    }

Of course, CORS must be enabled on API Gateway for each method used.

Upvotes: 2

Related Questions