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

좋은 웹페이지 즐겨찾기