Axios和Fetch有什么区别? [英] What is difference between Axios and Fetch?

查看:918
本文介绍了Axios和Fetch有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fetch调用Web服务,但是我可以在axios的帮助下进行相同的操作。所以现在我很困惑。我应该选择axios还是获取?

I am calling the web service by using fetch but the same I can do with the help of axios. So now I am confused. Should I go for either axios or fetch?

推荐答案

获取和Axios在功能上非常相似,但是为了实现向后兼容,Axios似乎为了更好地工作(例如,在IE 11中无法使用提取功能,请查看这篇文章

Fetch and Axios are very similar in functionality, but for more backwards compatibility Axios seems to work better (fetch doesn't work in IE 11 for example, check this post)

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

Also, if you work with JSON requests, the following are some differences I stumbled upon with.

获取JSON发布请求

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发布request

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
}

所以:


  • 获取的主体 = Axios的数据

  • 获取的正文必须进行字符串化,Axios的数据包含对象

  • 在请求中获取没有网址对象,Axios 在请求对象中具有URL

  • 获取请求函数包括 URL作为参数,Axios请求函数不将网址作为参数

  • 当响应对象包含 ok属性时,获取请求为确定,Axios请求为确定,当 status为200 并且 statusText为'OK'

  • 要获取json对象响应:在获取中调用响应对象上的 json()函数,在Axios中获取响应对象的 data属性

  • Fetch's body = Axios' data
  • Fetch's body has to be stringified, Axios' data contains the object
  • Fetch has no url in request object, Axios has url in request object
  • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
  • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

希望这会有所帮助。

这篇关于Axios和Fetch有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆