Javascript

Uncaught (in promise) TypeError: response.json is not a function

끈끈 2023. 4. 28. 00:41

 

todo > views.py:

class TodoShow(APIView):
    permission_classes = [permissions.IsAuthenticated]

    # 할일 조회
    def get(self, request, user_id):
        user = get_object_or_404(User, id=user_id)
        if request.user == user:
            todo = Todo.objects.filter(user_id=user_id)
            serializer = TodoSerializer(todo, many=True)
            print(serializer.data)
            return Response(serializer.data, status=status.HTTP_200_OK)

 

index.js:

async function TodoShow() {
    const payload = localStorage.getItem("payload")
    const user_parse = JSON.parse(payload).user_id
    const response = fetch('http://127.0.0.1:8000/todo/' + user_parse + '/', {
        headers: {
            "Authorization": "Bearer " + localStorage.getItem("access")
        },
        method: 'GET',
    })
    console.log(response)
    response_json = await response.json()

    console.log(response_json)
    response_json.forEach(todo => {
        content.innerHTML += "<div>" + todo.title + "</div>"
    });
}

 

 

console.log(response_json)

 

Uncaught (in promise) TypeError: response.json is not a function

 

 

response.json() 메소드에서 GET 요청이 들어오지 않고 위와 같은 error가 뜨며

 

Response 객체가 아닌 Promise 객체가 반환되는 문제 발생! 터미널에 print도 아무것도 뜨지 않음

 

fetch() 메소드가 반환한 response 객체에 json() 메서드가 정의되어 있지 않아 발생한 오류라고 한다

 


 

해결 방법

 

index.js

 

await 키워드를 빠져먹은 것이었다!

 

모두 잘 들어오는 것을 확인할 수 있다

 

console.log(response_json)

 

print(serializer.data)

 

'Javascript' 카테고리의 다른 글

자바스크립트의 비동기 처리  (2) 2023.05.08
Javascript의 비교 연산자  (2) 2023.05.01
innerHTML innerText textContent 차이점  (1) 2023.05.01
문자열 자르기 substr()  (1) 2023.04.28
Javascript Broken pipe from error  (4) 2023.04.28