How do I make an HTTP request in Javascript?

How do I make an HTTP request in Javascript?How do I make an HTTP request in Javascript?


There are several ways to make an HTTP request in JavaScript, but the most common ways are using the XMLH ttpRequest object or using the fetch() function.

 

Using XMLH ttp Request:

var  xhr = new XMLH ttpRequest();

xhr .open("GET", "http://example.com", true);

x hr .send();

Using fetch():

fetch("http://example.com")

  .then(response => response. Text())

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

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

Both the above examples perform a GET request to the specified URL. To perform a POST request, use "POST" as the first argument in the open() method or fetch() function and also specify the data to be sent in the request body.

 

It is important to note that fetch() only support modern browser. you might want to consider using Axioms or a super agent library that has better browser compatibility

 

Please let me know if you need more examples or have further questions.

Post a Comment

Previous Post Next Post