【问题标题】:AWS Lambda & API Gateway - 500 from browser but not from curlAWS Lambda 和 API Gateway - 来自浏览器的 500 但不是来自 curl
【发布时间】:2019-02-03 09:37:31
【问题描述】:

我正在努力使用 AWS Lambda 和 API Gateway。我可以从 curl 和 Postman 调用我的 API,但不能从我的浏览器调用。

这行得通

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/'

这不起作用 (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

【问题讨论】:

  • 您能否从您的 lambda 获取日志,或者将其配置为在响应中返回异常和堆栈跟踪?您能否在浏览器的网络工具中检查请求正文以确保它与 curl 正文相同?
  • 其实这可能是 CORS 问题。您是否为 CORS 设置了 Lambda?

标签: javascript jquery rest aws-lambda aws-api-gateway


【解决方案1】:

正如@Rup 在 cmets 中所说,这可能是一个 CORS 问题。从 .ajax() 的 contentType 选项上的 JQuery documentation 可以看到:

对于跨域请求,将内容类型设置为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 以外的任何内容都会触发浏览器向服务器发送预检 OPTIONS 请求

通过检查浏览器上的网络选项卡,您会看到它正在发送OPTION 请求。事实上,只需删除contentType 参数,您的代码就会按预期运行。

【讨论】:

    【解决方案2】:

    API 网关和 Lambda 的集成模式是什么 - 是基于代理的还是早期的?

    您是否在 API 网关方法中启用了 CORS。 https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2022-01-21
      • 1970-01-01
      • 2022-07-19
      • 2017-12-06
      • 1970-01-01
      • 2018-06-03
      • 2017-11-20
      • 2023-03-05
      相关资源
      最近更新 更多