HTTP request in Javascript Get JSON data with xhr method and fetch methods

HTTP request in Javascript?

There are several ways to make an HTTP request in JavaScript, including using the XMLHttpRequest object or the fetch() function.

Here is an example of making an HTTP GET request using XMLHttpRequest:

var xhr = new XMLHttpRequest();

xhr.open(“GET”, “https://example.com”);

xhr.send();

Here’s an example of making an HTTP GET request to a JSON endpoint using the XMLHttpRequest object and parsing the response as JSON:

var xhr = new XMLHttpRequest();

xhr.open(“GET”, “https://example.com/data.json”);

xhr.onload = function() {

    if (xhr.status === 200) {

        var data = JSON.parse(xhr.responseText);

        console.log(data);

    } else {

        console.error(xhr.statusText);

    }

};

xhr.onerror = function() {

    console.error(xhr.statusText);

};

xhr.send();

In this example, a new XMLHttpRequest object is created, and then opened with the “GET” method and the specified JSON endpoint URL. The onload event is used to handle the response, and onerror event is used to handle any error. The xhr.status is checked and if it’s 200, it indicates that the request is successful, then we parse the response as JSON and

log the data to the console. If the xhr.status is not 200, it means there’s an error and it logs the error message in the onerror function. If there’s any network error, the onerror function is triggered, and it logs the error message.

Finally the request is sent using the xhr.send() method.

Please note that you should always check the response status code and handle it accordingly. Also, XMLHttpRequest is an old API, and fetch() is more modern and recommended

The fetch() method is a modern JavaScript method that allows you to make HTTP requests, similar to the XMLHttpRequest object. The fetch() method returns a promise that resolves to the response of the request, which can be a Response or Error object.

When you call the fetch() method, you pass in the URL of the endpoint you want to make the request to. You can also pass in an options object as the second parameter, which allows you to configure the request, such as setting the HTTP method, headers, and body.

The fetch() method returns a promise that resolves to the response of the request. Once you have the response, you can use the .json(), .text(), .blob() methods, etc to access the data of the response.

Here’s an example of how you can use the fetch() method:

fetch(“https://example.com/data.json”)

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(error => console.log(error));

In this example, the fetch() method is used to make a GET request to a JSON endpoint. The .then() method is used to handle the response, which is passed as a parameter to the first callback function. The response.json() method is used to parse the response as JSON and the result is passed to the second callback function. Finally, the data is logged to the console. If there’s any error during the request, it will be caught and logged by the catch function.

The fetch() method is a more modern and recommended way to make HTTP requests in JavaScript, it’s more concise and easy to use, and it’s supported in most modern browsers.

And here is an example of making an HTTP GET request using fetch():

fetch(“https://example.com”)

  .then(response => response.text())

  .then(data => console.log(data))

  .catch(error => console.log(error));

The first example uses the XMLHttpRequest object to create a new request, open it with the “GET” method and the specified URL, and then send it. The response to the request can then be handled using the onload or onerror events.

The second example uses the fetch() function to make the same GET request to the specified URL, and then uses the .then() method to handle the response, which is passed as a parameter to the first callback function. The response is transformed to text and then logged in the second callback function. If there’s any error during the request, it will be caught and logged by the catch function.

Here’s an example of making an HTTP GET request to a JSON endpoint using the fetch() function and parsing the response as JSON:

fetch(“https://example.com/data.json”)

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(error => console.log(error));

The fetch() function is used to make the GET request to the specified JSON endpoint. The response.json() method is then used to parse the response as JSON and the result is passed to the first callback function. In the second callback function, the data is logged. If there’s any error during the request, it will be caught and logged by the catch function.

const output = document.querySelector(‘.output’);

const url = ‘https://www.discoveryvip.com/shared/person1000.json’;

const xhr = new XMLHttpRequest();

xhr.open(‘GET’,url);

xhr.onload = function(){

   if(xhr.status === 200){

       const data = JSON.parse(xhr.responseText);

       maker(data);

   }else{

       console.error(xhr.statusText);

   }

}

xhr.onerror = function(){

   console.error(xhr.statusText);

}

xhr.send();

output.innerHTML += ‘<hr>’;

fetch(url)

   .then(res => res.json())

   .then(data =>   maker(data))

   .catch(error => console.log(error));

function maker(data){

   data.forEach(ele =>{

       output.innerHTML += `

       <div>${ele.name.first} ${ele.name.last} ${ele.age}</div>

       <small>${JSON.stringify(ele)}</small>`;

   })

   output.innerHTML += ‘<hr>’;

}

JSON Code

[

   {

     “name”: {

       “first”: “Laurence”,

       “last”: “Svekis”

     },

     “age”: 40,

     “location”: {

       “city”: “Toronto”,

       “country”: “Canada”

     }

   },

   {

     “name”: {

       “first”: “Lisa”,

       “last”: “Suekis”

     },

     “age”: 30,

     “location”: {

       “city”: “New York”,

       “country”: “USA”

     }

   },

   {

     “name”: {

       “first”: “Johyn”,

       “last”: “Sekis”

     },

     “age”: 50,

     “location”: {

       “city”: “New York”,

       “country”: “USA”

     }

   }

 ]