If you are web developer and working with the front-end, then you might need to make HTTP requests to back-end code to get data or post data, so in this article, I have mentioned various possible ways to make HTTP requests in javascript.
There are multiple ways to make HTTP requests in JavaScript, but here are five of the most common approaches:
1. XMLHttpRequest (XHR) Object
The XMLHttpRequest (XHR) object is a built-in JavaScript API that allows you to send HTTP or HTTPS requests and receive responses. It supports both synchronous and asynchronous requests, but asynchronous requests are recommended to avoid blocking the main thread. Here is an example of sending an asynchronous GET request using XHR:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/users');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
2. Fetch API
The Fetch API is a modern replacement for XHR, and it is simpler to use and more flexible. It returns a Promise that resolves to the response object, which can be handled using the then() method or async/await syntax. Here is an example of sending an asynchronous GET request using Fetch:
fetch('https://example.com/users')
.then(response => response.json())
.then(data => console.log(data));
Browser Support for fetch API looks good, all modern browsers support Fetch API.
Using ES7 async/await, this becomes more simple as shown below
async function fetchAsync (url) {
let response = await fetch(url);
let data = await response.json();
return data;
}
3. Using jQuery Library
jQuery is a popular JavaScript library with a simplified HTTP API for making AJAX requests.
It supports both GET and POST requests, and it automatically parses the response data based on the content type.
Here is an example of sending an asynchronous GET request using jQuery:
$.get('https://example.com/users', function(data) {
console.log(data);
});
or for POST request
var formData = {name:"Test",age:"11"}; //Array
$.ajax({
url : "AJAX_POST_URL",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
4. Axios Library
Axios is a popular third-party library that simplifies making HTTP requests.
It supports both browser and Node.js environments, and it has built-in features such as request cancellation, interceptors, and error handling.
Here is an example of sending an asynchronous GET request using Axios:
axios.get('https://example.com/users')
.then(response => console.log(response.data));
5. Angular HttpClient
The HttpClient
is smaller, easier and powerful library for making HTTP requests. To use HttpClient
, we need to import HttpClientModule in our application module and then we can inject HttpClient in our components or services.
The HttpClient
methods are get(), post(), delete(), put() etc
The HttpClient
serves the purpose to perform HTTP requests. The HttpClient is an injectable class that performs HTTP GET request, using HttpClient.get
method. It accepts URL as string and options as object for parameters, headers etc, and returns an Observable instance. When we subscribe this Observable instance, HTTP GET request is executed on the server.
get(url: string, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: HttpObserve;
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
withCredentials?: boolean;
} = {}): Observable<any>
url
: Endpoint URL to post the data.
options
: Object type.The HttpClient.get has following options to request HTTP GET method.
headers
: It is of HttpHeaders types. It sets headers for the http GET request.
Note: For all of these approaches, you can also send POST requests by specifying the method as 'POST' and passing a data object or FormData as the body. as shown in jQuery POST request.
You may also like to read:
Google places autocomplete example without Map in Javascript
Preview Images before upload using Javascript
Get image width and height using Javascript and jQuery