我使用Fetch调用web服务,但我可以在Axios的帮助下做同样的事情。现在我很困惑。我应该选择Axios还是Fetch?
当前回答
axios的好处:
变形:允许在发出请求之前或在收到响应之后对数据进行转换 拦截器:允许您完全更改请求或响应(包括头)。也执行异步操作之前提出请求或承诺解决之前 内置XSRF保护
axios相对于fetch的优点
其他回答
根据mzabriskie在GitHub上的说法:
总的来说,它们非常相似。axios的一些好处: 变形:允许在发出请求之前或在接收到响应之后对数据进行转换 拦截器:允许您完全更改请求或响应(包括头)。另外,在请求被发送之前执行异步操作 在承诺解决之前 内置XSRF保护
请检查浏览器支持Axios
我认为您应该使用axios。
fetch API和axios API之间还有一个主要区别
在使用service worker时,只有当您想拦截HTTP请求时才必须使用fetch API 当使用service worker在PWA中执行缓存时,如果你使用axios API(它只适用于fetch API),你将无法缓存。
它们是HTTP请求库…
我最终也产生了同样的怀疑,但这篇文章中的表格让我选择了同构取回。它是fetch,但适用于NodeJS。
http://andrewhfarmer.com/ajax-libraries/
上面的链接失效了 同样的表格在这里:https://www.javascriptstuff.com/ajax-libraries/
或者在这里:
Axios是一个独立的第三方包,可以使用NPM轻松安装到React项目中。
你提到的另一个选项是fetch函数。与Axios不同,fetch()内置于大多数现代浏览器中。使用fetch,您不需要安装第三方包。
所以这取决于你,你可以使用fetch(),如果你不知道你在做什么,可能会搞砸,或者只是使用Axios,在我看来更直接。
Fetch和Axios在功能上非常相似,但为了更多的向后兼容性,Axios似乎工作得更好(例如,Fetch在IE 11中不能工作,请查看这篇文章)。
此外,如果您使用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
}
So:
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.
推荐文章
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 相当于字符串。jQuery格式
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?