HttpMessageNotReadableException, JSON parse error: Unrecognized token

    ChatGPT를 관리하는 프로그램을 만드는 도중, 오랜만에 웹을 건드리니 익숙하지 않아서 그런지 아래와 같은 에러가 발생하였다. 

     

    실행 화면

     

    에러 메세지

    [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'prompt': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'prompt': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 8]]

     

    jQuery로 Controller에게 Post값을 Ajax 형태로 전달을 하고 있는데 발생한 에러이고, 전달하는 data값이 파싱하기 힘들게 와서 에러를 발생하는 것 같았다.

     

    에러 코드

    // test button action
    $("#testBtn").click(function(){
        var prompt = $('#test_prompt_text').val();
        
        $.ajax({
            type: 'POST',
            url: "/gpt-gateway/v1/prompt",
            contentType: "application/json",
            data : ({
            	prompt_text : prompt
            }),
            dataType: "json",
            success: function(data){
                alert('success');
            },
            error : function(data){
                console.log("오류가 발생하였습니다.");	// 에러시 실행 할 내용
            }
        })
    });

     

    구글링한 결과 원인은 data를 JSON 포맷으로 만들지 못해서 생기는 문제였다. 방법은 매우 간단하였는데, JSON.stringify로 data 값을 감싸면 되었다.

     

    해결코드

    // test button action
    $("#testBtn").click(function(){
        var prompt = $('#test_prompt_text').val();
        //var data = "prompt=" + prompt;
    
        $.ajax({
            type: 'POST',
            url: "/gpt-gateway/v1/prompt",
            contentType: "application/json",
            data : JSON.stringify({
                prompt_text : prompt
            }),
            dataType: "json",
            success: function(data){
                alert('success');
            },
            error : function(data){
                console.log("오류가 발생하였습니다.");	// 에러시 실행 할 내용
            }
        })
    });

     

    실행결과

    [nio-8081-exec-4] [a.a.g.a.controller.GptGatewayController [request->RequestGptGatewayDTO(prompt_text=동해물과 백두산이 마르고 닳도록, max_tokens=0, temperature=0.0, top_p=0.0)

     

    반응형

    'Stackoverflow > Web' 카테고리의 다른 글

    Uncaught SyntaxError: Unexpected token 'export'  (0) 2023.04.28

    댓글

    Designed by JB FACTORY