Table of contents
Fetch
Fetch also integrates advanced HTTP concepts such as CORS and other extensions to HTTP.
// Example POST method implementation:
async function postData(url = "", data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json", // 'Content-Type': 'application/x-www-form-urlencoded',
}, redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData("https://example.com/answer", {answer: 42}).then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});
Body
Both requests and responses may contain body data. A body is an instance of any of the following types:
ArrayBufferTypedArray (Uint8Array and friends)DataViewBlobFileString, or a string literalURLSearchParamsFormData
The Request and Response interfaces share the following methods to extract a body. These all return a promise that is eventually resolved with the
actual content.
Request.arrayBuffer() / Response.arrayBuffer()Request.blob() / Response.blob()Request.formData() / Response.formData()Request.json() / Response.json()Request.text() / Response.text()
XMLHTTPRequest
function reqListener() {
console.log(this.responseText);
}
const req = new XMLHttpRequest();
req.addEventListener("load", reqListener);
req.open("GET", "https://www.example.org/example.txt");
req.send();
const xhttpr = new XMLHttpRequest();
xhttpr.open('GET', 'Api_address', true);
xhttpr.send();
xhttpr.onload = () => {
if (xhttpr.status === 200) {
const response = JSON.parse(xhttpr.response);
// Process the response data here
}
else {
// Handle error
}
};
Types of requests
A request made via
XMLHttpRequestcan fetch the data in one of two ways,asynchronouslyorsynchronously
The type of request is dictated by the optional async argument (the third argument) that is
set on theXMLHttpRequest.open()method.
If this argument is true or not specified, theXMLHttpRequestis processedasynchronously, otherwise the process is handledsynchronously.
A detailed discussion and demonstrations of these two types of requests can be found on thesynchronousandasynchronousrequests page.
You can’t usesynchronous requestsoutsideweb workersas it freezes the
main interface.
Axios
import axios from 'axios';
axios.get('APIURL')
.then(response => {
const responsedata = response.data; // Access
// Process the response data here
})
.catch(error => {
// Handle any errors
)
};
JQuery Ajax
$.ajax({
url: 'APIURL'
method: 'GET', success: function (response) {
const parsedData = JSON.parse(response);
// Process the parsed data here
}, error: function (xhr, status, error) {
// Handle any errors
});