我使用 Fetch 调用 Web 服务,但在 Axios 的帮助下我也可以做同样的事情。所以现在我很困惑。我应该选择 Axios 还是 Fetch?
请您参考如下方法:
Fetch 和 Axios 在功能上非常相似,但为了向后兼容,Axios 似乎工作得更好(例如 fetch 在 IE 11 中不起作用,请检查 this post )
此外,如果您使用 JSON 请求,以下是我偶然发现的一些差异。
获取 JSON post 请求
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请求
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的数据
- Fetch 的主体必须字符串化,Axios 的数据包含对象
- Fetch 请求对象中没有 url,Axios 请求对象中有 url
- Fetch请求函数包含url作为参数,Axios请求函数不包含url作为参数。
- 当响应对象包含ok属性时,Fetch请求是ok,当状态为200时,Axios请求是ok> 和 statusText 为“确定”
- 获取 json 对象响应:在 fetch 中调用响应对象的 json() 函数,在 Axios 中获取响应对象的 data 属性。