Tuesday, March 14, 2023

Make an HTTP request in JavaScript

You can make an HTTP request in JavaScript using the built-in XMLHttpRequest object or the newer fetch API.

Here is an example of making an HTTP GET request using XMLHttpRequest:

Javascript
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/api/data'); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error('Error:', xhr.status); } }; xhr.send();

And here is an example of making the same request using fetch:

Javascript
fetch('https://example.com/api/data') .then(response => { if (response.ok) { return response.text(); } throw new Error('Network response was not ok.'); }) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

Both of these examples make an HTTP GET request to https://example.com/api/data. The XMLHttpRequest example uses a callback function to handle the response, while the fetch example uses promises. You can use either method depending on your preference and the needs of your project.

No comments:

Post a Comment

Top5 free websites for download movies

CleverGet. Archive.Org. O2tvseries. YTS. AZmovies