Anas Latique
Anas Latique

Reputation: 408

AWS API GATEWAY <=> AWS Lambda CORS problem

This is my first time with AWS, I did set up a DynamoDB table as well as created Lambda functions to do CRUD manipulations, I made the functions static at first. Then, I proceeded to create API Gateway methods to access the Lambda functions dynamically.

The method that I try to call is a GET method, it should be callable using JS and from a different domain, I need to enable CORS, unfortunately even after I have it in the header of my lambda function it gives me CORS error:

'use strict';
const AWS = require('aws-sdk');

AWS.config.update({ region: 'us-east-2' });

exports.handler = async (event, context) => {
    const ddb = new AWS.DynamoDB({ apiVersion: '2012-10-08' });
    const documentClient = new AWS.DynamoDB.DocumentClient({ region: 'us-east-2' });
    let responseBody = "";
    let statusCode = 0;

    var params = {
    TableName: "Users",
  };

  // scan is a function, that is like the SELECT .. WHERE .. clause in SQL
    try{
        const data = await documentClient.scan(params).promise();
        responseBody = JSON.stringify(data.Items);
        statusCode = 200;
    }catch(err) {
        responseBody = `Unable to Scan Users, error: ${err}`;
        statusCode = 403;
    }

    const response = {
        statusCode: statusCode,
        headers: {
            "access-control-allow-origin": "*"
        },
        body: {
            responseBody
        }
    };

    return response;
};

This is the code I have in a VueJS application that should make a request to the GET method in API Gateway:

try{
  const res = await axios.get("https://here-goes-my-url");
  console.log(res.data);
} catch (err){
  console.log(err);
}

this is the error I'm getting:

Access to XMLHttpRequest at 'https://here-goes-the-url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The Lambda GET method should return all items in the table "Users". Please help, thanks!

Upvotes: 0

Views: 628

Answers (1)

frank3stein
frank3stein

Reputation: 706

Ok you have your header set.

Have you enabled cors from the API Gateway ?

enter image description here

And when you see CORS errors, they are not always related to CORS in case of AWS lambda as sometimes the response is blocked by API Gateway and the client is still getting a CORS error. I think this is made so it is more difficult to hack, as errors are useful if you are trying to hack the server.

So I would strongly suggest you to test your application first in the API Gateway console.

enter image description here

enter image description here

This will give you a more actionable error. I am guessing this might be related to permissions. Hope this helps.

Upvotes: 1

Related Questions