In JavaScript, both Axios and the native Fetch API are used to make HTTP requests, but they have some differences in terms of features, ease of use, and functionality. Here's a breakdown:
Axios:
Axios simplifies making requests and handling responses. It automatically parses JSON responses, making it easier to work with.
axios.get('/api/user') .then(response => console.log(response.data)) .catch(error => console.error(error));
Fetch:
With fetch, you need to explicitly handle JSON parsing, which adds an extra step.
fetch('/api/user') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
Fetch:
With fetch, non-2xx status codes (like 404 or 500) are not treated as errors. You have to manually check the response status and throw an error if needed.
fetch('/api/user') .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.json(); }) .then(data => console.log(data)) .catch(error => console.error(error));
Axios:
Axios provides built-in interceptors, allowing you to modify requests or handle responses globally, which can be useful for adding authentication tokens, logging, etc.
axios.interceptors.request.use(config => { config.headers['Authorization'] = 'Bearer token'; return config; });
Fetch:
Fetch does not have built-in interceptors, so you need to manually wrap the fetch call in a custom function if you need this behavior.
Axios:
Axios automatically stringifies data when making POST requests and sets the Content-Type to application/json. It also supports sending data in other formats like FormData with ease.
axios.post('/api/user', { name: 'John' });
Fetch:
In fetch, you need to manually stringify data and set the headers for POST requests.
fetch('/api/user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John' }) });
Axios:
Axios has built-in support for canceling requests using CancelToken.
const source = axios.CancelToken.source(); axios.get('/api/user', { cancelToken: source.token }); source.cancel('Request canceled.');
Fetch:
With fetch, you would need to use AbortController to cancel requests, which can be a bit more complex.
const controller = new AbortController(); fetch('/api/user', { signal: controller.signal }); controller.abort();
If you prefer more control over your requests, you might stick with fetch. If you want something that simplifies HTTP requests, axios would be the better option.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3