浅谈 Axios 和 Fetch 的区别
1.简单区分

2.请求方式
axios传一个对象,里面包含请求url和请求方法,参数。 fetch传两个参数,第一个是请求url,第二个是请求的一些参数。
// axios请求:
const options = {
url: "http://yuque.com/",
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json;charset=UTF-8",
},
data: {
yuque:'123'
},
};
axios(options).then((response) => {
console.log(response.status);
});
// fetch请求示例:
const url = "http://yuque.com/";
const options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json;charset=UTF-8",
},
body: JSON.stringify({
yuque:'123'
}),
};
fetch(url, options).then((response) => {
console.log(response.status);
});
3.同时请求
// axios
axios.all([
axios.get("http://yuque.com/one"),
axios.get("http://yuque.com/two"),
])
.then(
axios.spread((obj1, obj2) => {
...
})
);
// fetch
Promise.all([
fetch("http://yuque.com/one"),
fetch("http://yuque.com/two"),
])
.then(async ([res1, res2]) => {
const a = await res1.json();
const b = await res2.json();
})
.catch((error) => {
console.log(error);
});
4.请求的数据
在 axios 中,它是自动完成的,所以只需在请求中传递数据或从响应中获取数据。它是自动字符串化的,所以不需要其他操作。 在使用 fetch的时候,需要对响应数据使用某种方法,在发送带有请求的body时,需要对数据进行字符串化。 如下示例axios 没有额外的一行代码,在 fetch中,必须将数据转换为JSON格式。在一个较大的项目中,如果创建了大量的调用,那么可以使用 axios 来避免重复代码。
// axios
axios.get('url')
.then((response) => console.log(response))
.catch((error) => console.log(error))
// fetch
fetch('url')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error))
5.响应的使用
// axios
axios({
url: 'http://yuque.com/',
methods: 'POST',
timeout: 4000,
headers: {
Accept: "application/json",
'Content-Type': 'application/json;charset=UTF-8',
},
data: {
yuque:'123'
}
})
.then((response) => {
/* 处理响应 */
})
.catch((error) => console.log('请求超时'));
// fetch提供的属性AbortController
const controller = new AbortController();
const options = {
method: 'POST',
signal: controller.signal,
body: JSON.stringfy({
yuque:'123'
}),
};
const promise = fetch('http://yuque.com/',options);
const timeout = setTimeout(() => controller.abort(),4000);
promise
.then((response) => {
/* 处理响应*/
})
.catch((error) => console.log('请求超时'));
6.拦截的使用
// axios
axios.interceptors.request.use((config) => {
// 在请求之前对请求参数进行处理
return config;
});
axios.get("http://yuque.com/")
.then((response) => {
console.log(response.data);
});
// fetch
fetch = ((originalFetch) => {
return (...arguments) => {
const result = originalFetch.apply(this, arguments);
return result.then(console.log("请求已发送"));
};
})(fetch);
fetch("http:http://yuque.com/")
.then((response) => response.json())
.then((data) => {
console.log(data);
});
7.错误的处理
axios处理错误是非常容易的。如果出现像404这样的错误响应,promise就会被拒绝并返回一个错误,所以需要捕获一个错误,可以检查它是什么类型的错误。当响应良好时,接口返回了数据,但是如果请求以任何方式失败,使用axios就能够检查 .catch() 部分中的错误类型并返回正确的消息。 使用fetch,相对来说就较复杂了。每次从 fetch中得到响应时,需要检查状态是否成功,因为即使不是,也会得到响应。在 fetch的情况下,只有当请求没有完成时,promise才会被解决。
// axios
axios.get('url')
.then((response) => console.log(response))
.catch((error) => {
if (error.response) {
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if (error.request) {
console.log(error.request)
} else {
console.log(error.message)
}
})
// fetch
fetch('url')
.then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
return response.json()
})
.then((data) => console.log(data))
.catch((error) => console.log(error))
总结:
通过比较可以看出,对于较大型项目有大量http请求,需要良好的错误处理或http拦截的应用,Axios是一个更好的解决方案。在小型项目的情况下,只需要少量API调用,Fetch也是一个不错的解决方案。大多数浏览器和Node.js环境都支持Axios,而现在浏览器仅支持Fetch,所以使用H5或PC的项目使用Axios相对较好,使用App内嵌H5项目,依赖App壳子中的浏览器,尽量减少Fetch的使用,以达到最好的兼容性。
浙公网安备 33010602011771号