AWS Lambda & API Gateway - 500 from browser but not from curl

Viewed 1474

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

2 Answers

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.

Related