HTTP Request in Javascript

 To make an HTTP request in JavaScript, you can use the built-in fetch() function or the XMLHttpRequest object.


Here's an example using fetch():


javascript

Copy code

fetch('https://example.com/api/data')

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

  .then(data => {

    // handle the response data

    console.log(data);

  })

  .catch(error => {

    // handle the error

    console.error(error);

  });

In this example, fetch() is used to make a GET request to https://example.com/api/data. The response is returned as a Response object, which we can use the .json() method to extract the JSON response body. The second .then() callback receives the data, which can then be used as needed. If there was an error with the request, the .catch() callback will be executed.


Alternatively, you can use the XMLHttpRequest object to make the request:


javascript

Copy code

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://example.com/api/data');

xhr.onload = () => {

  if (xhr.status === 200) {

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

    // handle the response data

    console.log(data);

  } else {

    // handle the error

    console.error('Request failed.  Returned status of ' + xhr.status);

  }

};

xhr.send();

In this example, XMLHttpRequest is used to make a GET request to https://example.com/api/data. The onload callback is executed when the response is received. If the status code is 200, we can extract the JSON response body and use it as needed. Otherwise, we handle the error.

Comments

Popular posts from this blog

Online Money Making Tips

Aston Martin DB11

Tips for new Parents