Sitemap

How to make an HTTP Call || How to call API

2 min readDec 17, 2022

--

Today we are going to talk about how to make a network call in javascript

Press enter or click to view image in full size

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();

Press enter or click to view image in full size

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.

Press enter or click to view image in full size

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

--

--

Tasadduq Ali
Tasadduq Ali

Written by Tasadduq Ali

I am MERN Stack developer working in UAE Govt to digitize their massive services. I will help you to become highly skilled Coder 😉