简体   繁体   中英

why is the rest api call not working?

I am trying to fetch data by making an api call however the browser keeps showing xhr failed loading. i cant understand the mistake in my code.

function letsgo()
{
   var ourRequest = new XMLHttpRequest();
   ourRequest.open('GET','https://newsapi.org/v1/articles?source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58',true);

  ourRequest.onload = function()
  {
    if (ourRequest.status >= 200 && ourRequest.status < 400) 
    {

      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
    }
    else
    {
      console.log("We connected to the server, but it returned an error.");
    }

  };

  ourRequest.onerror = function() {
      console.log("Connection error");
  };

  ourRequest.send(); 
}

below is the function which logs the data

 function renderHTML(data) {
       console.log(data);
    }

Here is sample Code. This Codes works fine.

<html>
<link rel="stylesheet" 
 href=
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script 
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>

<body>
<script>
    $(document).ready(function () {

        function renderHTML(data) {
            console.log(data);
        }

        function letsgo() {
            var ourRequest = new XMLHttpRequest();
            ourRequest.open('GET',
                'https://newsapi.org/v1/articles?
source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58',
                true);

            ourRequest.onload = function () {
                if (ourRequest.status >= 200 && ourRequest.status < 400) {

                    var ourData = JSON.parse(ourRequest.responseText);
                    renderHTML(ourData);
                } else {
                    console.log("We connected to the server, but it returned 
an error.");
                }

            };

            ourRequest.onerror = function () {
                console.log("Connection error");
            };

            ourRequest.send();
        }

        letsgo();
    })
</script>
</body>
</html>

Your method of fetching data is a bit old, recently all major browsers are supporting fetch api

You can use it like:

 fetch('https://newsapi.org/v1/articles?source=techcrunch&apiKey=083f90f14c7d4a8b8346a5f944dedd58') .then(r => r.json()) .then(data => { document.getElementById("root").innerText = JSON.stringify(data, 0, 2) }) 
 <pre id="root"> </pre> 

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