HTTP GET requests retrieve information or data from a source (server) over the web.
GET requests have no body, so the information that the source requires, in order to return the proper response, must be included in the request URL path or query string.
XMLHttpRequest (XHR) objects are used to interact with servers. It can make many kinds of requests and supports other forms of data.
XHR GET request boilerplate code:
// Create new object
const xhr = new XMLHttpRequest();
const url = "https://api-to-call.com/endpoint";
// Handle response
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
};
// Open request and send objects
xhr.open('GET',url);
xhr.send();
HTTP POST requests send new information to the source (server) that will receive it.
For a POST request, the new information is stored in the body of the request.
XHR POST request boilerplate code:
const xhr = new XMLHttpRequest;
const url = 'https://api-to-call.com/endpoint';
const data = JSON.stringify({id: '200'});
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
};
xhr.open('POST', url);
xhr.send(data);
The fetch() function:
fetch('https://api-to-call.com/endpoint').then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
return jsonResponse;
});
// Send request
fetch('https://api-to-call.com/endpoint',{
method: 'POST',
body: JSON.stringify({id: '200'})
}).then(response => {
// Convert response object into JSON
if (response.ok) {
return response.json();
}
// Handle errors
throw new Error('Request failed!');
}, networkError => console.log(networkError.message)
// Handle success
).then(jsonResponse => {
// Code to execute with jsonResponse
});
const getData = async () => {
try {
const response = await fetch('https://api-to-call.com/endpoint');
if (response.ok) {
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch (error) {
console.log(error);
}
}
const getData = async () => {
try {
const response = await fetch('https://api-to-call.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: 200})
})
if(response.ok){
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch(error) {
console.log(error);
}
}