乐闻世界logo
搜索文章和话题

What is difference between axios and fetch?

4个答案

1
2
3
4

axios and fetch are both popular tools for making HTTP requests in JavaScript environments. They are commonly used to communicate with servers, but they have distinct characteristics. Below are some key differences:

1. Native Support

  • fetch: This is a native API provided by modern browsers and can be used without additional libraries. It is part of the standard Web API.
  • axios: This is a third-party library that can be installed via npm. It offers more features and better error handling but requires external setup.

2. Usage

  • fetch: The API is more native and low-level. It does not automatically convert JSON data; developers must manually call the .json() method for conversion. For example:
    javascript
    fetch('/some/url') .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('There was a problem with your fetch operation:', error));
  • axios: This library provides a more user-friendly interface. It automatically handles JSON conversion and includes built-in features for error handling. For example:
    javascript
    axios.get('/some/url') .then(response => console.log(response.data)) .catch(error => { if (error.response) { console.error('Error response', error.response.status); } else if (error.request) { console.error('Error request', error.request); } else { console.error('Error', error.message); } });

3. Error Handling

  • fetch: Resolves the promise when the request is successfully sent and the server responds, even for HTTP error status codes like 404 or 500. It only rejects in cases of network failures or blocked requests. This means developers must check the response.ok property after each call to handle errors manually.
  • axios: Automatically rejects when the response status code is outside the 2xx range (e.g., 404 or 500), which simplifies error handling. It also provides detailed error objects for easier debugging.

4. Timeout Settings

  • fetch: Does not have native timeout support. Developers need to implement their own logic to handle timeouts, such as using Promise.race with a timeout promise.
  • axios: Allows you to directly set the timeout property in the request configuration (e.g., axios.get('/url', { timeout: 5000 })), making it more straightforward.

5. Cross-platform

  • fetch: Primarily used in browser environments. While libraries like node-fetch can simulate the Fetch API in Node.js, it is not natively supported there.
  • axios: Can be used in both browser and Node.js environments, providing better cross-platform compatibility.

6. Request Cancellation

  • fetch: Supports cancellation via AbortController in modern browsers, but this is a relatively new feature and may not be supported in older browsers.
  • axios: Supports request cancellation via cancel tokens, which is more reliable and easier to use.

7. Request Progress

  • fetch: Does not support monitoring upload or download progress. It lacks built-in functionality for this.
  • axios: Provides progress event updates during uploads and downloads, which is useful for user feedback.

8. Security

  • fetch: Follows the same-origin policy and can handle cross-origin requests using CORS.
  • axios: Also follows the same-origin policy and supports CORS, with additional features for security headers.

Example of handling 404 errors with fetch:

javascript
fetch('/some/url') .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('There was a problem with your fetch operation:', error));

Example of handling 404 errors with axios:

javascript
axios.get('/some/url') .then(response => console.log(response.data)) .catch(error => { if (error.response) { console.error('Error response', error.response.status); } else if (error.request) { console.error('Error request', error.request); } else { console.error('Error', error.message); } });

In practical applications, choosing between axios and fetch depends on project requirements. If you require more built-in features and the project environment permits the use of external libraries, axios may be a good choice. If you prefer to minimize dependencies and use native APIs, then fetch might be more suitable. Both are common HTTP client libraries used to initiate network requests in web applications.

2024年6月29日 12:07 回复

When discussing Axios and fetch, we refer to two different methods for making HTTP requests in JavaScript. Here are several key differences between them:

1. Browser Support

  • fetch: is a built-in API of modern browsers, requiring no additional libraries or frameworks. The fetch() method is supported by all modern browsers but not by Internet Explorer.
  • Axios: is a third-party library that needs to be installed via npm or added via a script tag in HTML. It works with XMLHttpRequest in older browsers, thus providing better support for older browsers.

2. JSON Data Handling

  • fetch: does not automatically convert JSON response bodies; you need to manually call the .json() method to parse JSON data.
  • Axios: automatically converts JSON data into JavaScript objects, meaning you can directly use the response data without additional parsing steps.

3. Error Handling

  • fetch: resolves the promise even for HTTP error responses (e.g., 404 or 500 status codes), unless a network error prevents the request from completing.
  • Axios: automatically rejects the promise when non-2xx response codes are returned, making error handling more straightforward.

4. Request and Response Interceptors

  • Axios: allows you to intercept requests or responses before they are handled by then or catch, which can be used for adding common parameters, handling responses, etc.
  • fetch: has no built-in interceptor functionality, but this can be simulated by adding logic where fetch() is called.

5. Request Cancellation

  • Axios: supports canceling ongoing requests, which is implemented using a cancel token (CancelToken).
  • fetch: natively does not support canceling requests, but in modern browsers, it can be canceled using the AbortController interface.

6. Request Timeout

  • Axios: allows directly setting request timeouts.
  • fetch: natively does not provide a way to set timeouts, but this can be implemented with additional code.

7. HTTP Interface

  • Axios: automatically handles request and response headers, processes HTTP status codes, and provides richer API configuration options.
  • fetch: has a relatively simple API, but may require more wrapper code to achieve the same functionality.

Examples

Suppose we want to make a GET request to an API endpoint to retrieve user data:

Using Axios

javascript
axios.get('https://api.example.com/users') .then(response => { console.log(response.data); }) .catch(error => { console.error('An error occurred:', error); });

Using fetch

javascript
fetch('https://api.example.com/users') .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('An error occurred:', error); });

In both examples, Axios automatically handles JSON parsing, whereas with fetch, we must manually call .json(). Additionally, Axios provides richer error handling, while fetch requires checking response.ok in each request. The choice of which method to use primarily depends on specific project requirements, compatibility needs, and the developer's personal preference.

2024年6月29日 12:07 回复
  • Another key difference between the fetch API and the axios API
  • When using Service Workers, you must use the fetch API when intercepting HTTP requests.
  • Additionally, when using Service Workers for caching in PWA, using the axios API will prevent caching (it is only applicable to the fetch API).
2024年6月29日 12:07 回复

Fetch and Axios are functionally similar, but for backward compatibility, Axios is generally preferred (for example, fetch does not work in IE 11; see this article).

Additionally, if you're using JSON requests, here are some differences I discovered.

Fetch JSON POST Request

javascript
let url = 'https://someurl.com'; let options = { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, body: JSON.stringify({ property_one: value_one, property_two: value_two }) }; let response = await fetch(url, options); let responseOK = response && response.ok; if (responseOK) { let data = await response.json(); // do something with data }

Axios JSON POST Request

javascript
let url = 'https://someurl.com'; let options = { method: 'POST', url: url, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8' }, data: { property_one: value_one, property_two: value_two } }; let response = await axios(options); let responseOK = response && response.status === 200 && response.statusText === 'OK'; if (responseOK) { let data = await response.data; // do something with data }

So:

  • Fetch's body = Axios's data
  • Fetch's body must be stringified, while Axios's data contains an object
  • Fetch request objects have no url property, while Axios request objects include the url property
  • The fetch request function includes url as a parameter, whereas the axios request function does not include url as a parameter.
  • For fetch requests, the response is considered successful when it has the ok property; for Axios requests, it's successful when the status is 200 and statusText is 'OK'.
  • To get JSON response objects: in fetch, call the json() method on the response object; in Axios, access the data property of the response object.
2024年6月29日 12:07 回复

你的答案