axios 백엔드 호출 후 리턴 받는 방법


필자는 리액트를 개발하는 중이다.
React, redux Saga를 이용해 Spring Boot와 Rest Api 통신을 한다.

원래는 아래와 같이 데이터를 받았다.

- api.js -

export const getData = async () => {
    try {
        const res = await axois.get(restApiurl);
                    .catch((error) => {
                        return error;   
                    });
       return res.data
    } catch(e) {
         console.log(e);
    }     
};

만약 디비에서 에러가 나서 HttpStatus  500 에러가 났다고 가정해 보자.
아무리 에러 보내도 try catch 문에 잡히지 않고..
. catch(error)에도 걸리지 않는다.
환장할 노릇이다. ㄷㄷㄷㄷㄷㄷ
테스트해 보니 백엔드가 먹통일 때만 catch문에 걸림...ㅠㅠ
그러니까.  이 상태로는 이벤트 핸드링을 하기 어렵다는 것임.

그렇다면 아래와 같이 수정해 보자!!

export const getData = async () => {
    try {
        return await axois.get(restApiurl, {validateStatus: () => true});
                    .then(function(response) {
                        //console.log(response)
                        return response.data
                     }
                     .catch(function(error) => {
                        return error;   
                     });
    } catch(e) {
         console.log(e);
    }     
};

위 코드를 보면 .then, .error 구문에 function() 을 넣어주었다!!

이렇게 해서 console.log(response)를 찍어보면 에러코드가 나온다!!!
이때 url을 전송할 때 validateStatus: () => true 를 같이 보내면 리턴 받는 것들을 json 형태로 받을 수 있다.

엄청나게 구글링 해서 얻은 결과!! 뿌듯하다!!

도움 되셨거나 더 많이 아시는 분들은 댓글 달아주세요^^
소통은 저에게 힘이 된답니다. ㅎㅎ

+ Recent posts