How do I make an HTTP request in Javascript?

Mustafa Ali
By -
0

How do I make an HTTP request in Javascript?

To make an HTTP request in Javascript, you can use the XMLHttpRequest object or the fetch function.



In JavaScript, you can make an HTTP request using the XMLHttpRequest object or the newer fetch API. Here's an example of how to make a GET request using XMLHttpRequest:

javascript
const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api/data'); xhr.send(); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('Request failed. Returned status of ' + xhr.status); } };

Here's an example of how to make a GET request using the fetch API:

javascript
fetch('http://example.com/api/data') .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.log(error));

You can also make POST requests with both XMLHttpRequest and fetch. For example, with XMLHttpRequest:

javascript
const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://example.com/api/data'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ data: 'some data' })); xhr.onload = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('Request failed. Returned status of ' + xhr.status); } };

And with fetch:

javascript
fetch('http://example.com/api/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: 'some data' }) }) .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.log(error));

Note that in these examples, we're assuming that the API at http://example.com/api/data returns data in JSON format. If the API returns data in a different format, you may need to adjust the code accordingly.

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Ok, Go it!