To make an HTTP request in Javascript - IndianDeal

IndianDeal

Indian deal is providing latest offers and news beneficial for the students and to the job seekers.

Breaking

Post Top Ad

Friday, 10 March 2023

To make an HTTP request in Javascript

 To make an HTTP request in Javascript

You can use the built-in XMLHttpRequest object or the newer fetch() method. Here are examples of both:

Using XMLHttpRequest:

javascript
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api/data', true); xhr.onload = function() { if (this.status === 200) { console.log('Success!', this.response); } else { console.error('Error:', this.statusText); } }; xhr.onerror = function() { console.error('Network Error'); }; xhr.send();

Using fetch():

javascript
fetch('http://example.com/api/data') .then(function(response) { if (response.ok) { return response.json(); } throw new Error('Network response was not ok.'); }) .then(function(data) { console.log('Success!', data); }) .catch(function(error) { console.error('Error:', error); });

In both cases, you need to specify the URL of the resource you want to access. For XMLHttpRequest, you also need to specify the HTTP method (e.g. GET, POST, etc.) and whether the request should be asynchronous or not. The onload and onerror callbacks are used to handle the response and any errors that might occur.

For fetch(), you use the Promise API to handle the response and errors. The ok property of the response object is used to check if the request was successful, and the json() method is used to extract the response body as a JSON object.

Daily offers

Post Bottom Ad