How do I make an HTTP request in Javascript?
To make an HTTP request in Javascript, you can use the built-in fetch function or the XMLHttpRequest object. Here are examples of how to use each approach:
Using the fetch function:
javascriptfetch('https://example.com/data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In the above example, we use fetch to retrieve data from an API endpoint, which returns a Promise that resolves to the response from the server. We then use the json method on the response to extract the JSON data from the response. Finally, we log the data to the console.
Using the XMLHttpRequest object:
javascriptconst xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json');
xhr.onload = function() {
if (xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
console.log(data);
} else {
console.error(`Request failed. Returned status of ${xhr.status}`);
}
};
xhr.send();
In this example, we create an instance of the XMLHttpRequest object and use the open method to set up the request. We then set the onload event handler to handle the response from the server. If the status code is 200, we extract the JSON data from the response using JSON.parse and log it to the console. If the status code is not 200, we log an error message to the console. Finally, we send the request using the send method.
Comments
Post a Comment