How to make an HTTP Call || How to call API
Today we are going to talk about how to make a network call in javascript
To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch() API.
Here is an example of how to use the XMLHttpRequest object to make an HTTP GET request to fetch some data from a server:
Code
var xhr = new XMLHttpRequest();
xhr.open(‘GET’, ‘https://www.example.com/data.json', true);
xhr.onload = function () {
if (this.status == 200) {
var data = JSON.parse(this.responseText);
// Do something with the data here
}
};
xhr.send();
And here is an example of how to use the fetch() API to make the same request:
//code
fetch(‘https://www.example.com/data.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
// Do something with the data here
});
Note that the fetch() method returns a Promise, so you need to use the then() method to handle the response.
Both examples assume that the ‘HTTP :// www.example.com/textfile.txt' URL returns a text file. You can adjust the URL and the code accordingly to make requests to other URLs and handle different types of responses.
Kindly do let me know if you have any questions regarding anything. I would love to help and guide you. Just ping me on Instagram at https://www.instagram.com/codeculturepro/ or at codeculturepro@gmail.com
