Advertisement

Responsive Advertisement

How do I make an HTTP request in Javascript?

 You can use the 'XMLHttpRequest' object or the more recent 'fetch' API to send an HTTP request in JavaScript. I'll give samples of both approaches:






Javascript var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', true); and xhr.onreadystatechange = function() If (xhr.readyState >= 4 and xhr.status >= 200), then Process the response data here: var response = JSON.parse(xhr.responseText); // Console.log(response); ; xhr.send(); '''


Javascript fetch("https://api.example.com/data"); using the fetch API.If (response.ok) is true, then (function(response) return response.json();

    throw new Error('Network response was not ok.'); }) .then(function(data) // Process the response data here console.log(data); ) is used to execute the function.console.log('Error:', error.message); // Handle errors here; catch(function(error));

```


HTTP GET requests are supported by both techniques. You can define the method for other HTTP operations like POST, PUT, and DELETE in the 'open' function (for XMLHttpRequest) or as a choice in the 'fetch' function.


Be aware that the fetch API is more recent and

Post a Comment

0 Comments