api 서버로 post 요청시 에러..

api 서버에 post 요청하는 내용을 html 로 간단하게 작성했는데요..

2가지 방법으로 요청했으나

{“type”:“RFC 7231 - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content Media Type”,“status”:415,“traceId”:“00-41808cde0d4cf94c3■■4e9d91e960223-076264ce7f4ffcdb-00”}

위와 같은 에러 메시지가 뜨면서 안됩니다. 제가 알기론 415 에러가 json 형식으로 데이터를 넘기지 않아서 그런걸로 알고 있는데요.

html 로 post 요청을 작성할 때 content type을 json 으로 해도 안되네요, (swagger 로 json 데이터 포함해서 post 요청하거나, postman 프로그램을 통해 json 데이터 포함해서 post 요청하면 잘 됩니다,..)

아래 html 코드는 제가 해 본 것 입니다, 무엇이 문제 일까요?

==========================
첫번째 html

<meta charset="UTF-8">

<title>JSON 파일 선택하기</title>
<form method="post" action="http://192.168.0.69:8080/api/withdraw" enctype="application/json">

    <input type="file" name="json_file" accept=".json">

    <button type="submit">전송</button>

</form>

====================
두번째 html
=-===================

<meta charset="UTF-8">

<title>JSON 파일 선택하기</title>
<form method="post" action="http://192.168.0.69:8080/api/withdraw" enctype="application/json">

    <input type="file" name="json_file" accept=".json" onchange="loadFile(event)">

    <button type="submit" onclick="sendJson()">전송</button>

</form>

<script>

    function loadFile(event) {

        const input = event.target;

        if ('files' in input && input.files.length > 0) {

            readJSON(input.files[0]);

        }

    }

    function readJSON(file) {

        const reader = new FileReader();

        reader.onload = function(event) {

            const contents = event.target.result;

            const jsonData = JSON.parse(contents);

            document.getElementById("json_data").value = JSON.stringify(jsonData);

        };

        reader.readAsText(file);

    }

    function sendJson() {

        const jsonData = document.getElementById("json_data").value;

        const xhr = new XMLHttpRequest();

        xhr.open("POST", "http://192.168.0.69:8080/api/withdraw");

        xhr.setRequestHeader("Content-Type", "application/json");

        xhr.send(jsonData);

    }

</script>

<textarea id="json_data" style="display:none;"></textarea>
2 Likes

클라이언트 측 json 데이터 요청 방법이 틀렸습니다.

위처럼 그냥 html의 form 태그로 post 요청 하시면

아마 form-data 컨텐츠로 요청될것입니다.

그래서 415코드 반환 되었을거구요


웹 프론트에서 json 요청은 자바스크립트의 ajax 등을 통해
json 데이터로 요청하셔야합니다.

3 Likes

const settings = {
“async”: true,
“crossDomain”: true,
“url”: “https://localhost:7008/api/tokens”,
“method”: “POST”,
“headers”: {
“Content-Type”: “application/json”
},
“processData”: false,
“data”: “{\n "email": "mail”,\n "password": "xxxx"\n}"
};

$.ajax(settings).done(function (response) {
console.log(response);
});

이런식으로 보내야 될것예요 XMLHttpRequest ??이것 예전에 soap 할때 쓰던것 같네요

3 Likes

답변 감사합니다 !!! 한번 해볼게요

2 Likes

답변 감사합니다!! ajax 라는 걸로 검색해서 해볼게요

2 Likes

jquery를 이용한 ajax post method 예시

    $.ajax({
        type: "POST",
        url: "/api/cart/getCart",
        async: false,
        contentType: "application/json", //보내는 데이타 type
        data: JSON.stringify(sendData), // formdata등을 json으로 변환
        dataType: "json", // 받는 데이타 type
        success: function (data) {
            alert("정상");
        },
        error: function (xhr) {
            alert("에러");
        }
    });

보내는 데이타를 JSON.stringify하지 않아서 415오류를 받았을 겁니다.
그리고, fetch등을 이용한 방법도 있습니다.

3 Likes