Ajax 对 AWS 的请求 API 网关无法解析 json 响应

Ajax Request to AWS API Gateway can not parse json response

我正在测试这里的代码: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get

代码如下:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var processJSON =  function(data, textStatus, xhr) {
       alert(xhr.status);
    }
// for whatever reason, the following URL is not working any more, so you won't be able to test it anymore.
  var myURL='https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223';
//  var myURL="https://jsonplaceholder.typicode.com/users"

    $("button").click(function(){
        $.ajax({
          url: myURL,
          dataType: "json",
          contentType: 'application/json',
          success: processJSON
        });


    });
});
</script>
</head>
<body>

<button>Send Request</button>

</body>
</html>

如代码中所示,我正在尝试解析此 URL 的响应: https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223

您可以直接转到 URL 并发现 AWS-API-Gateway 的响应很简单:

{
 "cc":"dd",
 "name":"ee"
}

我能够使用上面的 javascript 来解析来自其他来源的其他 json 响应。但是我正在拉扯我的头发试图解析来自 AWS-API-Gateway 的上述响应。 如果您取消注释 var myURL 的第二行,您会发现该代码确实适用于其他 URL。

==========

回应现有答案:

你的 API 为我工作。可能没关系,但我没有使用 'resp' 作为变量标签,而是使用 'data'.

此外,调用命名函数而不是内嵌函数

    function processJSON(data) {
      alert(data.name);
    }

          dataType: "json",
          contentType: 'application/json',

这是数据类型。您告诉 jQuery 期待 jsonp 回调。您正在寻找的是 dataType: "json".


更新

我刚刚测试了你的代码。问题是您没有在 pettest/test 资源中定义 OPTIONS 方法。使用 API 网关控制台,打开测试资源(假设 pettest 是阶段,test 是资源),然后使用 "Actions" 下拉按钮启用 CORS。这将自动创建 OPTIONS 方法并在 GET 方法中设置所需的 headers。