Axios 和 Fetch 有什么区别?

What is difference between Axios and Fetch?

我正在使用 Fetch 调用 Web 服务,但在 Axios 的帮助下我也可以这样做。所以现在我很困惑。我应该选择 Axios 还是 Fetch?

它们是 HTTP 请求库...

我也有同样的疑问,但是 post 中的 table 让我选择了 isomorphic-fetch。这是 fetch 但适用于 NodeJS。

http://andrewhfarmer.com/ajax-libraries/


上面的link已经死了 同样的table在这里:https://www.javascriptstuff.com/ajax-libraries/

或在这里:

根据 mzabriskie on GitHub:

Overall they are very similar. Some benefits of axios:

  • Transformers: allow performing transforms on data before a request is made or after a response is received

  • Interceptors: allow you to alter the request or response entirely (headers as well). also, perform async operations before a request is made or before Promise settles

  • Built-in XSRF protection

请检查浏览器是否支持 Axios

我认为你应该使用 axios。

此外...我在测试中使用了各种库,注意到它们对 4xx 请求的处理方式不同。在这种情况下,我测试 returns 具有 400 响应的 json 对象。这是 3 个流行的库处理响应的方式:

// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)


// node-fetch
const body = await fetch(url)
console.log(await body.json())


// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)

有趣的是 request-promise-nativeaxios 会引发 4xx 响应,而 node-fetch 不会。 fetch 也使用 json 解析的承诺。

Fetch 和 Axios 在功能上非常相似,但为了更多的向后兼容性,Axios 似乎工作得更好(例如,fetch 在 IE 11 中不起作用,检查 this post

此外,如果您使用 JSON 请求,以下是我偶然发现的一些差异。

获取JSONpost请求

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
}

axiosJSONpost请求

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
}

所以:

  • Fetch 的 body = Axios 的 data
  • Fetch 的主体必须 stringified,Axios 的数据包含 object
  • Fetch 请求对象中没有url,Axios 请求对象中有url
  • fetch请求函数包含url作为参数,axios请求函数不包含url作为参数[=47] =].
  • 当响应对象包含 ok 属性 时,获取请求 ok,Axios 请求 ok status 为 200 并且 statusText 为 'OK'
  • 获取json对象响应:在fetch中调用响应对象上的json()函数,在Axios中获取响应对象的数据属性

axios 的好处:

  • 变形金刚:允许在发出请求之前或收到响应之后对数据执行转换
  • 拦截器:允许您完全改变请求或响应(headers)。还在发出请求之前或 Promise 结算之前执行异步操作
  • Built-in XSRF 保护

Advantages of axios over fetch

Axios 是一个独立的第 3 方包,可以使用 NPM 轻松安装到 React 项目中。

您提到的另一个选项是获取功能。与 Axios 不同,fetch() 内置于大多数现代浏览器中。使用 fetch,您无需安装第三方包。

所以这取决于你,你可以选择 fetch() 如果你不知道自己在做什么或者只使用我认为更直接的 Axios 可能会搞砸。

fetch API 和 axios API

之间的另一个 主要区别
  • 在使用 service worker 时,如果要拦截 HTTP 请求,则必须 仅使用 fetch API
  • 例如。使用 service worker 在 PWA 中执行缓存时,如果您使用的是 axios API(它仅适用于 fetch API)
  • ,您将无法缓存

使用fetch,我们需要处理两个promise。使用axios,我们可以直接访问响应对象数据属性.

中的JSON结果
  1. Fetch API,需要处理两个promise才能得到JSONObject属性中的响应数据。而 axios 结果为 JSON object.

  2. fetch 中的错误处理也不同,因为它不处理 catch 块中的服务器端错误,从 fetch() 返回的 Promise 不会拒绝 HTTP 错误状态,即使响应是 HTTP 404 或 500。相反,它将正常解析(将 ok 状态设置为 false),并且它只会在网络故障或任何阻止请求完成的情况下拒绝。在 axios 中,您可以捕获 catch 块中的所有错误。

我会说最好使用 axios,直接处理拦截器,headers 配置,设置 cookie 和错误处理。

Refer this

我似乎经常做的一项工作是通过 ajax 发送表单,通常包括一个附件和几个输入字段。在更经典的工作流程 (HTML/PHP/JQuery) 中,我在客户端使用了 $.ajax(),在服务器上使用了 PHP,并且完全成功。

我已经为 dart/flutter 使用了 axios,但现在我正在学习 React 来构建我的网站,JQuery 没有意义。

问题是 axios 让我有些头疼 PHP 另一方面,当发布两个正常输入字段并以相同的形式上传文件时。我在 PHP 中尝试了 $_POSTfile_get_contents("php://input"),使用 FormData 从 axios 发送或使用 json 构造,但我永远无法同时获得文件上传和输入字段。

另一方面,使用 Fetch,我使用这段代码取得了成功:

var formid = e.target.id;

// populate FormData
var fd    = buildFormData(formid);       

// post to remote
fetch('apiurl.php', {
  method: 'POST',
  body: fd,
  headers: 
  {
     'Authorization' : 'auth',
     "X-Requested-With" : "XMLHttpRequest"
  }
})    

在 PHP 方面,我能够通过 $_FILES 检索上传并通过 $_POST:

处理其他字段数据
  $posts = [];
  foreach ($_POST as $post) {
      $posts[] =  json_decode($post);
  }

A​​xios 是一个基于承诺的 HTTP 客户端库,而 Fetch 是一个 javascript API 用于发出 API 请求。

  1. 主要区别在于浏览器支持:Axios 支持包括 IE 在内的所有浏览器,而 Fetch 仅受最新浏览器支持,IE 不支持。

引用link:https://github.com/axios/axios#browser-support

https://caniuse.com/fetch

  1. 与 fetch API 相比,Axios 具有更好的错误处理能力。 Axios 可以抛出 400 到 500 个范围状态代码错误,而在 fetch API 中你需要手动处理错误。 更多:https://bariablogger.in/f/axios-vs-fetch-react