How to make an HTTP request in Javascript?

4
(1)

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

Here’s an example of making an HTTP request using fetch():

fetch('https://example.org/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

This code sends an HTTP GET request to https://example.com/data.json, and when the response is received, it is converted to JSON using the json() method of the response object. Then, the JSON data is logged to the console.

Here’s an example of making an HTTP request using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json');
xhr.onload = () => {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error(xhr.statusText);
  }
};
xhr.onerror = () => {
  console.error('Network error');
};
xhr.send();

This code creates a new XMLHttpRequest object, opens a connection to https://example.com/data.json, and defines a callback function to handle the response. If the response status is 200 (OK), the response text is logged to the console. If there is an error, an error message is logged to the console. Finally, the request is sent using the send() method.

385

How useful was this post?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top