fetch와 axios의 비교
9163 단어 javascriptbeginners
1.겟
술책
fetch(url)
.then((res) => {
if (!res.ok) {
// need error handling here
throw Error();
}
// need conversion
return res.json();
})
.then((data) => {
// use this data
})
.catch((error) => // error handling )
.finally(() => // this is optional);
액시오스
GET 메소드를 사용할 때 .get을 생략할 수 있습니다.
axios.get(url)
.then((response) => {
const data = response.data;
// use this data directly
})
.catch((error) => // error handling)
.finally(() => // this is optional);
2. 포스트
술책
fetch(url,
{
method: "POST",
// you can omit headers nowadays
headers: {
"Content-Type": "application/json",
},
// need conversion
body: JSON.stringify(
{
tag: data.tag,
imageUrl: url,
})
})
.then((res) => {
// need error handling here
if (!res.ok) {
throw Error();
}
})
.catch((error) => { // error handling });
액시오스
axios.post(url,
{
// you can put an object directly
tag: data.tag,
imageUrl: url,
})
.then((res) => { // success operations})
.catch((error) => { // error handling });
3. 삭제
술책
fetch(url,
{
method: "DELETE",
})
.then((res) => {
// need error handling here
if (!res.ok) {
throw Error();
}
// success operation
})
.catch((error) => { // error handling })
액시오스
axios.delete(url)
.then((*res*) => {
// success operation
})
.catch((error) => setError("Delete failed"))
.finally(() => setLoading(false));
결론
설치 및 가져오기의 번거로운 프로세스를 수행해야 하지만 많은 개발자가 axios를 선호하는 이유를 마침내 이해합니다. axios는 fetch보다 훨씬 간단하며 throwing 오류를 잊어버리기 때문에 무의식적인 버그를 피할 수 있습니다. 따라서 저는 이제부터 axios를 사용할 것입니다.
읽어 주셔서 감사합니다.
조언이나 피드백을 댓글로 남겨주시면 기쁩니다. :)
원문은 here
Reference
이 문제에 관하여(fetch와 axios의 비교), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/lada496/comparison-between-fetch-and-axios-4np2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)