ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [TIL] Back-end와 통신 시 발생하는 에러(Unexpected end of JSON input)
    Develope/React 2020. 7. 19. 21:55

    react logo

     

    ◎ 백엔드와 통신할 때 자주 목격한 에러에 대해 정리하겠다.

    1. 문제

    ◎ 백엔드와 통신할 때 Unexpected end of JSON input 에러 메시지를 몇 번 목격하였다.

    코드는 다음과 같다.

    handleGoCart = () => {
            const token = localStorage.getItem("access_token");
            const { productDetail , optionId, number } = this.state;
            fetch(`${API}/order/cart` , {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                     Authorization : token
                },
                body: JSON.stringify({
                    product_id : productDetail.product_id,
                    selected_option_id : optionId,
                    quantity : number 
                })
            })
            .then(res => res.json()) // error의 원인 
            .then(res => {
                if(res.status === 200) {
                    this.props.history.push(`/cart`);
                }else if(res.status === 400) {
                    alert("로그인이 필요한 서비스 입니다.")
                    this.props.history.push("/login");
                }
            }).catch(err => console.log("err: ", err))
        }
    

     

    error

    2. 원인

    ◎ 원인은 json을 바디에 안 담아주고 있다.

    받아온 response가 제대로 된 JSON 형태로 보내주는 것이 아니어서 에러가 발생한 것이다.

    3. 해결 방법

    res.json() 구문을 삭제하면 된다. 

    백엔드에서 JsonResponse 가 아닌 HttpResponse 를 보내주는 경우에 대한 에러핸들링 방법으로 res.status 의 200 여부에 ㄸ른 액션을 처리하는 로직을 구현했는데, 저기서 res.ok 를 확인하는 것도 한가지 방법이다.

    res.ok 는 Boolean value 라서 단순 성공/에러 여부만 확인하는 케이스면 조금 더 편하게 쓰는 방법이다.

    하지만 원인과 해결방법이 정확한 게 아닐 수 도 있기 때문에 이 문제에 대해서 좀 더 검색을 해봐야 할 거 같다.

    이 문제에 대해서는 백엔드가 어떠한 형식으로 보내주는지 소통이 필요한 부분 같다.

    handleGoCart = () => {
            const token = localStorage.getItem("access_token");
            const { productDetail , optionId, number } = this.state;
            fetch(`${API}/order/cart` , {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                     Authorization : token
                },
                body: JSON.stringify({
                    product_id : productDetail.product_id,
                    selected_option_id : optionId,
                    quantity : number 
                })
            })
            .then(res => {
                if(res.status === 200) {
                    this.props.history.push(`/cart`);
                }else if(res.status === 400) {
                    alert("로그인이 필요한 서비스 입니다.")
                    this.props.history.push("/login");
                }
            }).catch(err => console.log("err: ", err))
        }
    

     

     

Designed by Tistory.