How do I make an HTTP request in Javascript?
In JavaScript, you can make an HTTP request using the built-in XMLHttpRequest object or the newer fetch API. Here's an example of making an HTTP GET request using both methods:
Using XMLHttpRequest:
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 => response.text())
.then(data => console.log(data))
.catch(error => console.error(error));
Both methods allow you to specify the HTTP method, URL, and any additional headers or data to send with the request. You can also handle the response data and any errors that may occur.
Comments
Post a Comment