Home >Web Front-end >JS Tutorial >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.
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.
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.
axios(config) .then(response => console.log(response.data)) .catch(error => console.error('Error:', error));
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); } });
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.
First, install Axios using npm or yarn:
axios(config) .then(response => console.log(response.data)) .catch(error => console.error('Error:', error));
You can also include Axios via a CDN:
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); } });
Here’s how to use Axios to make a GET request:
npm install axios # or yarn add axios # or pnpm install axios
Since fetch() is built-in, you don't need to install anything. Here's how to make a GET request with fetch():
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
import axios from 'axios'; axios.get('https://example.com/api') .then(response => console.log(response.data)) .catch(error => console.error(error));
fetch('https://example.com/api') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
Axios:
fetch(url, options) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
Fetch:
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));
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 */ });
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 */ });
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 */ });
Axios:
Fetch:
Axios:
Handles errors in the catch block and considers any status code outside 2xx as an error:
async function getData() { try { const response = await axios.get('/api/data'); // handle response } catch (error) { // handle error } }
Fetch:
Requires manual status checking:
async function getData() { try { const response = await fetch('/api/data'); const data = await response.json(); // handle data } catch (error) { // handle error } }
There is no definitive answer as it depends on your requirements:
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.
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!
The above is the detailed content of Axios vs Fetch: Which is Best for HTTP Requests?. For more information, please follow other related articles on the PHP Chinese website!