Axios vs Fetch: Which is Best for HTTP Requests?
There are many ways to make HTTP requests in JavaScript, but two of the most popular ones are Axios
and the native fetch()
API. In this post, we will compare and contrast these two methods to determine which one is better suited for different scenarios.
Essential Role of HTTP Requests
HTTP requests are fundamental for communicating with servers and APIs in web applications. Both Axios
and fetch()
are widely used to facilitate these requests effectively. Let's dive into their features and see how they stack up.
What is Axios?
Axios is a third-party library that provides a promise-based HTTP client for making HTTP requests. It is known for its simplicity and flexibility and is widely used in the JavaScript community.
Basic Syntax of Axios
axios(config)
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
Key Features of Axios:
Configuration Flexibility: Accepts both a URL and configuration object.
Automatic Data Handling: Converts data to and from JSON automatically.
Error Handling: Automatically handles HTTP error status codes, passing them to the catch block.
Simplified Response: Returns server data directly in the
data
property of the response object.Streamlined Error Management: Provides a more streamlined error handling mechanism.
Example:
axios({
method: 'post',
url: 'https://api.example.com/data',
data: { key: 'value' }
})
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
console.error('Server responded with:', error.response.status);
} else if (error.request) {
console.error('No response received');
} else {
console.error('Error:', error.message);
}
});
Why Use Axios?
Automatic JSON Data Transformation: Converts data to and from JSON seamlessly.
Response Timeout: Allows setting a timeout for requests.
HTTP Interceptors: Lets you intercept requests and responses.
Download Progress: Tracks the progress of downloads and uploads.
Simultaneous Requests: Handles multiple requests simultaneously and combines responses.
What is Fetch?
fetch() is a built-in API in modern JavaScript, supported by all modern browsers. It is an asynchronous web API that returns data in the form of promises.
Features of fetch():
Basic Syntax: Simple and concise, takes a URL and an optional options object.
Backward Compatibility: Can be used in older browsers with polyfills.
Customizable: Allows detailed control over headers, body, method, mode, credentials, cache, redirect, and referrer policies.
How to Use Axios to Make HTTP Requests
First, install Axios using npm or yarn:
npm install axios
# or
yarn add axios
# or
pnpm install axios
You can also include Axios via a CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Here’s how to use Axios to make a GET request:
import axios from 'axios';
axios.get('https://example.com/api')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Making HTTP Requests with Fetch
Since fetch() is built-in, you don't need to install anything. Here's how to make a GET request with fetch():
fetch('https://example.com/api')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Notice that:
Data Handling: Axios automatically transforms the data to and from JSON, while with fetch() you must manually call
response.json()
.Error Handling: Axios handles errors within the catch block, while fetch() only rejects the promise on network errors, not on HTTP status errors.
Basic Syntax of Fetch
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Key Features:
Simple Arguments: Takes a URL and an optional configuration object.
Manual Data Handling: Requires manual conversion of data to string.
Response Object: Returns a Response object containing complete response information.
Error Handling: Needs manual checking of response status codes for HTTP errors.
Example:
fetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
})
.then(response => {
if (!response.ok) throw new Error('HTTP error ' + response.status);
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Comparison of Axios and Fetch
Sending GET Requests with Query Parameters
Axios:
axios.get('/api/data', { params: { name: 'Alice', age: 25 } })
.then(response => { /* handle response */ })
.catch(error => { /* handle error */ });
Fetch:
const url = new URL('/api/data');
url.searchParams.append('name', 'Alice');
url.searchParams.append('age', 25);
fetch(url)
.then(response => response.json())
.then(data => { /* handle data */ })
.catch(error => { /* handle error */ });
Sending POST Requests with a JSON Body
Axios:
axios.post('/api/data', { name: 'Bob', age: 30 })
.then(response => { /* handle response */ })
.catch(error => { /* handle error */ });
Fetch:
fetch('/api/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Bob', age: 30 })
})
.then(response => response.json())
.then(data => { /* handle data */ })
.catch(error => { /* handle error */ });
Setting a Timeout for the Request
Axios:
axios.get('/api/data', { timeout: 5000 }) // 5 seconds
.then(response => { /* handle response */ })
.catch(error => { /* handle error */ });
Fetch:
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000); // abort after 5 seconds
fetch('/api/data', { signal })
.then(response => response.json())
.then(data => { /* handle data */ })
.catch(error => { /* handle error */ });
Using async/await Syntax
Axios:
async function getData() {
try {
const response = await axios.get('/api/data');
// handle response
} catch (error) {
// handle error
}
}
Fetch:
async function getData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
// handle data
} catch (error) {
// handle error
}
}
Backward Compatibility
Axios:
Needs to be installed and included in your project.
Supports older browsers with polyfills for promises and other modern JavaScript features.
Actively maintained for compatibility with new environments.
Fetch:
Native support in modern browsers.
Can be polyfilled to support older browsers.
Automatically updated by browser vendors.
Error Handling
Axios:
Handles errors in the catch block and considers any status code outside 2xx as an error:
try {
const response = await axios.get('/api/data');
// handle response
} catch (error) {
console.log(error.response.data);
}
Fetch:
Requires manual status checking:
try {
const response = await fetch('/api/data');
if (!response.ok) throw new Error('HTTP error ' + response.status);
const data = await response.json();
// handle data
} catch (error) {
console.log(error.message);
}
Axios vs Fetch: Which is Best?
There is no definitive answer as it depends on your requirements:
Use Axios if you need features like automatic JSON data transformation, HTTP interceptors, and advanced error handling.
Use fetch() if you want a native, lightweight solution with extensive customization options.
Generate Axios/Fetch Code with EchoAPI
EchoAPI is an all-in-one collaborative API development platform offering tools for designing, debugging, testing, and mocking APIs. EchoAPI can automatically generate Axios code for making HTTP requests.
Steps to Generate Axios Code with EchoAPI:
1. Open EchoAPI and create a new request.
2. Enter the API endpoint, headers, and parameters, then click "Code snippet".
3. Select "Generate client code".
4. Copy and paste the generated Axios code into your project.
Conclusion
Both Axios
and fetch()
are powerful methods for making HTTP requests in JavaScript. Choose the one that best fits your project's needs and preferences. Utilizing tools like EchoAPI can enhance your development workflow, ensuring that your code is accurate and efficient. Happy coding!
Try EchoAPI Interceptor today! https://www.echoapi.com/plugin/chrome?utm_source=6715d073
Subscribe to my newsletter
Read articles from Issy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by