Type to search

Tags: ,

How does one make a HTTP request in Javascript?

Share

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch API.

XMLHttpRequest

The XMLHttpRequest object is a built-in JavaScript object that allows you to make HTTP requests from within your script. To use XMLHttpRequest, you need to create an instance of the object and then call its methods to send a request and handle the response.

Here is an example of how to use XMLHttpRequest to send a GET request to a server and log the response to the console:

// Create an instance of the XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Set the HTTP method and URL
xhr.open('GET', 'https://example.com/api/endpoint');

// Set the request header (if needed)
xhr.setRequestHeader('Content-Type', 'application/json');

// Send the request
xhr.send();

// Log the response when it is received
xhr.onload = function() {
console.log(xhr.response);
}

You can also use XMLHttpRequest to send other HTTP methods, such as POST, PUT, and DELETE, by changing the first argument of the open method. For example:

xhr.open('POST', 'https://example.com/api/endpoint');

In addition to sending requests and receiving responses, XMLHttpRequest also has a number of properties and methods that allow you to track the status of the request and handle errors. For example, you can check the status property to see if the request was successful (e.g. 200 for OK) and the responseText property to access the response data as a string.

Here is an example of how to use these properties and methods to handle errors and display a message to the user:

// Send the request
xhr.send();

// Handle the response
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.response);
} else {
console.error('An error occurred: ' + xhr.status);
}
}

// Handle network errors
xhr.onerror = function() {
console.error('Network error');
}

fetch

The fetch API is a newer way to make HTTP requests in JavaScript. It uses Promises, which makes it easier to work with asyncronous requests and handle errors.

To use fetch, you call the fetch function and pass it the URL of the server you want to make the request to. It returns a Promise that resolves with the Response object from the server.

Here is an example of how to use fetch to send a GET request to a server and log the response to the console:

fetch('https://example.com/api/endpoint')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error('An error occurred:', error);
});

Like XMLHttpRequest, you can use the fetch function to send other HTTP methods by passing an options object

Tags::