Which one should we use? Axios vs fetch()
In this article, we will compare the uses and differences of fetch() and Axios.
Fetch: The Fetch API provides a fetch() method defined on the window object. It also provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline (requests and responses).
Axios: Axios is a promise-based HTTP client for Node.js and the browser.
Syntax
// Example fetch() POST usage
const url = "https://foo-bar.com";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
x: "foo",
y: "bar",
}),
};
fetch(url, options)
.then((response) => response.json())
.then((data) => { console.log(data) });
- fetch() uses the “body” property while sending the data.
- The data in fetch() is transformed to a string using the JSON.stringfy method.
- With fetch(), you have to parse the data returned from the server to a Javascript object with the response.json() method.
- For fetch() method, the final data can be named any variable.
// Example Axios POST usage
const url = "https://foo-bar.com";
const data = {
x: "foo",
y: "bar",
};
axios
.post(url, data, {
headers: {
Accept: "application/json"
},
})
.then(({data}) => {
console.log(data);
});
- Axios automatically transforms the data returned from the server.
- With Axios, the data response provided by the server can be accessed within the data object.
JSON Data Transformation
// Axios
axios.get('https://foo-bar.com')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
// fetch()
fetch('https://foo-bar.com')
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => console.error(error));
- Axios automatically stringify the data when sending a request.
- Axios automatically parse the response to json.
- When using fetch(), you’d have to do it manually.
- Automatic transformation of data is a nice feature to have, but it’s not something you can’t do with fetch().
Simultaneous Requests
To make multiple simultaneous requests, Axios provides the axios.all() method. We pass an array of requests to this method, then use axios.spread() to assign properties of the response separate to individual variables.
axios.all([
axios.get('https://foo-bar-1.com'),
axios.get('https://foo-bar-2.com')
])
.then(axios.spread((x, y) => {
console.log(x.data);
console.log(y.data);
}));
We can achieve the same result using Promise.all().
Promise.all([
axios.get('https://foo-bar-1.com'),
axios.get('https://foo-bar-2.com')
])
.then(async([response1, response2]) => {
const x = await response1.json();
const y = await response2.json();
console.log(x.data);
console.log(y.data);
})
Backward Compatibility
One of the main uses of Axios is its wide browser support. The reason why even very old browser versions run Axios without problems is that it uses XMLHTTPRequest.
On the other hand, Fetch only supports these versions;
- Chrome 42+
- Firefox 39+
- Edge 14+
- Safari 10.3+
Response Timeout
The simplicity of setting the timeout in Axios causes most people to prefer it. In Axios, you can easily use the “timeout” property of the config object to set the number of milliseconds before the request is canceled.
// 15 seconds timeout added at axios config object.
// If the server does not respond within 15 seconds, the catch block runs.axios({
method: 'POST',
url: 'https://foo-bar.com',
timeout: 15000,
data: {
x: "foo",
y: "bar",
}
})
.then(response => console.log(response.data))
.catch(error => console.log('Timeout Error.!'))
Fetch provides the same functionality as the AbortController interface. Its use is not as simple as in Axios.
// 15 seconds timeout functionality with AbortController interface.
// If the server does not respond within 15 seconds, the catch block runs.const controller = new AbortController();
const options = {
method: 'POST',
signal: controller.signal,
body: JSON.stringify({
x: "foo",
y: "bar",
})
};
const promise = fetch('https://foo-bar.com', options);
const timeout = setTimeout(() => controller.abort(), 15000);
promise
.then(response => console.log(response.data))
.catch(error => console.log('Timeout Error.!'))
HTTP Interceptors
One of the most important features of Axios is; the ability to intercept HTTP requests. HTTP interceptors are useful when you need to examine or modify HTTP requests from your application to the server and vice versa (For example, logging, authentication, and retrying failed HTTP requests).
axios.interceptors.request.use(
config => {
// Handle smth (For example; token setting) before any HTTP request is sentreturn config;
},
error => {
Promise.reject(error);
});axios.interceptors.response.use(
response => response,
error => {
// Handle after response returns with some error (For example; retrying failed HTTP requests)Promise.reject(error);
});
By default, fetch() does not provide a way to intercept requests. But it is not difficult to find a temporary solution. A global fetch method can be prepared and requests can be handled on it.
Conclusion
Axios provides an easy-to-use API for HTTP communication requirements. It is entirely possible to recreate the core features of the Axios library using the fetch() method provided by web browsers. As a result, using or not using Axios depends on whether you are comfortable working with the built-in APIs.