📜  Fetch 和 Axios.js 发出 http 请求的区别

📅  最后修改于: 2022-05-13 01:56:48.400000             🧑  作者: Mango

Fetch 和 Axios.js 发出 http 请求的区别

任何 Web 应用程序的基本任务之一是通过 HTTP 协议与服务器通信。这可以使用 Fetch 或 Axios 轻松实现。 Fetch 和 Axios 在功能上非常相似。一些开发人员更喜欢 Axios 而不是内置 API,因为它易于使用。 Fetch API 完全能够重现 Axios 的关键特性。
Fetch: Fetch API 提供了一个在窗口对象上定义的fetch() 方法。它还提供了一个 JavaScript 接口,用于访问和操作部分 HTTP 管道(请求和响应)。 fetch 方法有一个强制参数——要获取的资源的 URL。此方法返回一个 Promise,可用于检索请求的响应。

  • 程序:
javascript
fetch('path-to-the-resource-to-be-fetched')
  .then((response) => {
 
    // Code for handling the response
  })
  .catch((error) => {
 
    // Code for handling the error
  });


javascript
axios.get('url')
  .then((response) => {
 
    // Code for handling the response
  })
  .catch((error) => {
 
    // Code for handling the error
  })


Axios: Axios 是一个 Javascript 库,用于从浏览器发出来自 node.js 或 XMLHttpRequests 的 HTTP 请求,它支持 JS ES6 原生的 Promise API。它可用于拦截 HTTP 请求和响应,并启用针对 XSRF 的客户端保护。它还具有取消请求的能力。

  • 程序:

javascript

axios.get('url')
  .then((response) => {
 
    // Code for handling the response
  })
  .catch((error) => {
 
    // Code for handling the error
  })

Axios 和 Fetch 的区别:

AxiosFetch
Axios has url in request object.Fetch has no url in request object.
Axios is a stand-alone third party package that can be easily installed.Fetch is built into most modern browsers; no installation is required as such.
Axios enjoys built-in XSRF protection.Fetch does not.
Axios uses the data property.Fetch uses the body property.
Axios’ data contains the object.Fetch’s body has to be stringified.
Axios request is ok when status is 200 and statusText is ‘OK’.Fetch request is ok when response object contains the ok property.
Axios performs automatic transforms of JSON data.Fetch is a two-step process when handling JSON data- first, to make the actual request; second, to call the .json() method on the response.
Axios allows cancelling request and request timeout.Fetch does not.
Axios has the ability to intercept HTTP requests.Fetch, by default, doesn’t provide a way to intercept requests.
Axios has built-in support for download progress.Fetch does not support upload progress.
Axios has wide browser support.Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+ (This is known as Backward Compatibility).