简体   繁体   中英

Ajax Request to AWS API Gateway can not parse json response

I am testing the code here: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get

Here is the code:

<!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>

As indicated in the code, I am trying to parse the response from this URL: https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223

And you can go to that URL directly and find out that the response from the AWS-API-Gateway is simply:

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

I was able to use the above javascript to parse other json responses from other sources. But I am pulling my hair trying to parse the above response from AWS-API-Gateway . if you uncomment the second line of var myURL , you will see that the code just really works for other URLs.

==========

In response to existing answers:

  • I tried both json and jsonp . Both worked for other URLs (including the one I commented). But neither works for the AWS Gateway API.
  • I also updated the code to use a named function. But again, it works for other URLs, but not for the AWS URL.
  • I tested it on Firefox and Safari.

It's the data type. You are telling jQuery to expect jsonp callback. What you are looking for is dataType: "json".


UPDATE

I just tested your code. Issue is that you don't have an OPTIONS method defined in your pettest/test resource. Using the API Gateway console, open the test resource (assume pettest is the stage and test is the resource), then use the "Actions" dropdown button to Enable CORS. This will automatically create the OPTIONS method and setup the required headers in your GET method.

Worked for me with your API. Probably doesn't matter, but instead of using 'resp' as the variable label, I used 'data'.

Also, calling a named function rather than embedding the function inline

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM