How do I make an HTTP request in Javascript XMLHttpRequest?

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the more modern fetch function.

Here is an example of how to use XMLHttpRequest to make a GET request to a server and parse the response:

// Create an XMLHttpRequest object
const xhr = new XMLHttpRequest();

// Set the request URL and method
xhr.open('GET', 'http://www.example.com/api/endpoint');

// Set the request header (optional)
xhr.setRequestHeader('Content-Type', 'application/json');

// Set the response type (optional)
xhr.responseType = 'json';

// Send the request
xhr.send();

// Handle the response
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    // Success!
    const data = xhr.response;
    console.log(data);
  } else {
    // Error :(
    console.error(xhr.statusText);
  }
};

xhr.onerror = function () {
  console.error(xhr.statusText);
};

Here is an example of how to use fetch to make a GET request to a server and parse the response:

fetch('http://www.example.com/api/endpoint')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Note that fetch returns a Promise, so you can use the then and catch methods to handle the response asynchronously.

You can also use fetch to make other types of HTTP requests, such as POST, PUT, and DELETE, by specifying the method and any required headers and body in the options object:

fetch('http://www.example.com/api/endpoint', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John',
    age: 30
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

πŸ“Œ Nodejs and Android 😎
πŸ“Œ Java

Articles: 444

Leave a Reply

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