How do I make an HTTP request in Javascript?

 To make an HTTP request in JavaScript, you can use the built-in XMLHttpRequest object or the newer fetch API. Here's an example of how to use both methods:



Using XMLHttpRequest:

javascript
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); console.log(response); } }; xhr.send();

Using fetch:

javascript
fetch('https://api.example.com/data') .then(function(response) { if (response.ok) { return response.json(); } throw new Error('Network response was not OK.'); }) .then(function(data) { console.log(data); }) .catch(function(error) { console.log('Error:', error.message); });

In both examples, we are making a GET request to the URL 'https://api.example.com/data'. The response from the server is then processed in the onreadystatechange event handler for XMLHttpRequest or in the then callback function for fetch. In the case of fetch, we handle any network errors using the catch method.

Note: The fetch API is more modern and provides a simpler and more flexible way to make HTTP requests. However, the XMLHttpRequest object is still widely supported in older browsers.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.