How do I make an HTTP request in JavaScript?

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch() function.
Here is an example of making an HTTP GET request using XMLHttpRequest:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
function makeRequest(method, url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.onload = function() { if (this.status >= 200 && this.status < 300) { resolve(xhr.response); } else { reject({ status: this.status, statusText: xhr.statusText }); } }; xhr.onerror = function() { reject({ status: this.status, statusText: xhr.statusText }); }; xhr.send(); }); } makeRequest('GET', 'http://example.com/api/data') .then(data => console.log(data)) .catch(error => console.error(error)); |
Here is an example of making an HTTP GET request using fetch():
1 2 3 4 |
fetch('http://example.com/api/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); |
Both examples make an HTTP GET request to the specified URL and log the response data to the console. The fetch() function is promise-based, so you can use .then() and .catch() to handle the response.
Note that these examples are for making GET requests. To make other types of HTTP requests (such as POST, PUT, DELETE, etc.), you will need to specify the HTTP method and possibly include a request body in the request. For example, to make a POST request with a request body, you can use the following code:
1 2 3 4 5 6 7 8 9 10 |
fetch('http://example.com/api/data', { method: 'POST', body: JSON.stringify({key: 'value'}), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); |
This makes a POST request to the specified URL with a JSON-formatted request body and sets the Content-Type header to application/json.
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]