How do I make an HTTP request in Javascript?

In Javascript, you can make HTTP requests using the built-in XMLHttpRequest object or the newer fetch() function. Here are examples of both: Using XMLHttpRequest: 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.log('Request failed. Returned status of ' + xhr.status); } }; xhr.send(); 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.log('Request failed. Returned status of ' + xhr.status); } }; xhr.send(); javascript Copy code 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.log('Request failed. Returned status of ' + xhr.status); } }; xhr.send(); Using fetch: javascript Copy code 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('There was a problem fetching the data:', error)); Both examples show how to make a GET request to the URL https://example.com/api/data. For other HTTP methods, such as POST or PUT, you can specify them as the first argument of xhr.open() or as an option in the fetch() call.

Post a Comment

कृपया संबंधित और शिष्ट कमेंट करें। स्पैम/लिंक हटाए जाएंगे। धन्यवाद!

Previous Post Next Post