3

I'm struggling with AWS Lambda and API Gateway. I can call my API fine from curl and Postman, but not from my browser.

This works

curl --header "Content-Type: application/json" \
     --request POST \
     --data '{ "baseId" : "app0ZJgZxm6LC8rBB", "tableName": "Stories", "action": "select" }' \
     'https://gpzy1rrcwg.execute-api.us-east-1.amazonaws.com/Prod/'

This does NOT work (link to run it on CodePen)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            type: 'POST',
            url: 'https://gpzy1rrcwg.execute-api.us-east-1.amazonaws.com/Prod/',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({
                "baseId" : "app0ZJgZxm6LC8rBB",
                "tableName": "Stories",
                "action": "select"
            }),
            success: function (response) {
                console.log(response)
                alert('it worked')
            },
            error: function (err) {
                console.log(err)
                alert('it failed')
            }
        });
    });
});
</script>
</head>
<body>

<button>Test</button>

</body>
</html>

link to run it on CodePen

SGT Grumpy Pants
  • 4,118
  • 4
  • 42
  • 64
  • Can you get logs from your lambda, or configure it to return exceptions and stack traces in the response? Can you check the request body in your browser's network tools to make sure it's the same as the curl body? – Rup Aug 28 '18 at 17:15
  • Actually this might be a CORS issue. Have you set up your Lambda for CORS? – Rup Aug 28 '18 at 17:17

2 Answers2

4

It is probably a CORS problem, as @Rup said in the comments. From the JQuery documentation on the contentType option for .ajax() you see this:

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server

By checking the network tab on your browser you will see it is sending an OPTION request. In fact, by simply removing the contentType parameter your code will run as expected.

Pedro Henrique
  • 601
  • 6
  • 17
0

What is the Integration Mode between API gateway and Lambda - Is it Proxy based or the earlier one.?

Have you enabled CORS in your API Gateway Method.? https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

trnrao
  • 86
  • 1
  • 2