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 built-in XMLHttpRequest object or the newer fetch() function. Here's an example of each approach:

Using XMLHttpRequest:

javascript                       
var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://api.example.com/data', true); xhr.onload = function() { if (xhr.status === 200) { var response = JSON.parse(xhr.responseText); // Handle the response data } }; xhr.onerror = function() { // Handle error }; xhr.send();

Using fetch():

javascript
fetch('https://api.example.com/data') .then(function(response) { if (response.ok) { return response.json(); } else { throw new Error('Error: ' + response.status); } }) .then(function(data) { // Handle the response data }) .catch(function(error) { // Handle error });

In both cases, you specify the URL of the API you want to call (https://api.example.com/data in the examples). For more advanced use cases, you can also specify additional options such as headers, request type (GET, POST, etc.), and request data.

Note: The fetch() function is supported in most modern browsers, but for older browsers, you might need to use a polyfill or fallback to XMLHttpRequest.

Previous Post Next Post