One of the fundamental tasks of a frontend application is to communicate with servers through the HTTP protocol. JavaScript can send network requests to the server and load new information whenever needed without reloading the page.
The term for that kind of operation is Asynchronous JavaScript And XML (AJAX), which uses the XMLHttpRequest object to communicate with the servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.
In this guide, we will be looking at how to make a network request to get information from the server asynchronously with the fetch() API and Axios and learn how they can be used to perform different operations.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch()
method that provides an easy, logical way to fetch resources asynchronously across the network.
The fetch()
method takes one mandatory argument—the path to the resource you want to fetch—and returns a Promise that resolves with an object of the built-in Response class as soon as the server responds with headers.
The code below demonstrates a very basic fetch request in which we are fetching a JSON file across the network.
fetch('examples/example.json')
.then((response) => {
// Do stuff with the response
})
.catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
The second argument that the fetch()
method takes is the request object.
{
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'
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
}
Once a Response
is retrieved, the returned object contains the following properties:
response.body
: A simple getter exposing a ReadableStream of the body contentsresponse.bodyUsed
: Stores a Boolean that declares whether the body has been used in a response yetresponse.headers
: The headers object associated with the responseresponse.ok
: A Boolean indicating whether the response was successful or notresponse.redirected
: Indicates whether or not the response is the result of a redirectresponse.status
: The status code of the responseresponse.statusText
: The status message corresponding to the status coderesponse.type
: The type of the responseresponse.url
: The URL of the responseThere are a number of methods available to define the body content in various formats:
response.json()
: Parse the response as JSONresponse.text()
: Read the response and return as textresponse.formData()
: Return the response as FormData objectresponse.blob()
: Return the response as Blobresponse.arrayBuffer()
: Return the response as ArrayBufferAxios is a Javascript library used to make http requests from node.js
or XMLHttpRequests
from the browser, and it supports the Promise API that is native to JS ES6.
Some core features of Axios, according to the documentation, are:
Axios does not come as a native JavaScript API, so we will have to manually import into our project. To get started, we will have to include the following commands:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
npm install axios
bower install axios
And make a request as follows:
axios.get('examples/example.json')
.then((response) => {
// handle success
console.log(response);
})
.catch((error) => {
// handle error
console.log(error);
})
Axios also provides more functions to make other network requests as well, matching the HTTP verbs that you wish to execute, such as:
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
You can check out the comprehensive request config in the official documentation.
The response from a request contains the following information:
response.data
: The response provided by the serverresponse.status
: The HTTP status code from the server responseresponse.statusText
: HTTP status message from the server responseresponse.headers
: The headers that the server responded withresponse.config
: The config that was provided to axios
for the requestresponse.request
: The request that generated this responseWe’re now familiar with the definitions and usage of axios
and fetch()
. Let’s focus our attention on how to perform some real world operations with both Axios and Fetch.
#axios #javascript #programming #developer