How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript?


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


Here's an example of using XMLHttpRequest to make a GET request to a server:


function makeRequest(url) {

const xhr = new XMLHttpRequest();




xhr.onreadystatechange = function() {

if (xhr.readyState === XMLHttpRequest.DONE) {

if (xhr.status === 200) {

console.log(xhr.responseText);

} else {

console.error('An error occurred: ' + xhr.status);

}

}

};




xhr.open('GET', url, true);

xhr.send();

}


You can call the make Request function with a URL as an argument to make a GET request to that URL.


Here's an example of using fetch() to make a GET request:

fetch(url)

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

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

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

The fetch() function returns a Promise that resolves with a Response object. You can call the text() method on the Response object to get the response body as a string.


You can also use fetch() to make other types of HTTP requests, such as POST, PUT, and DELETE, by passing an options object as the second argument. For example:


fetch(url, {

  method: 'POST',

  body: JSON.stringify({

    name: 'John',

    message: 'Hello World'

  }),

  headers: {

    'Content-Type': 'application/json'

  }

})

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

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

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

This example makes a POST request to the specified URL with a JSON body and sets the Content-Type header to application/json. The response.json() method parses the response body as JSON.

Kaleem Khan

I'm Kaleem Khan Citizen of Pakistan. Student Of Bachelor of Computer Science at the Virtual University Of Pakistn.

Post a Comment

Please Don't Advertise or Spam Links and Messages Here.

Previous Post Next Post

Recent Posts

Recent Posts