티스토리 뷰

에러 메세지

회원가입 로직을 테스트하는 중에 해당 문제가 발생했습니다.

클라이언트에서 POST 방식으로 요청을 보낼 수 있는 API를 만들어서 전달했는데, 요청 시 아래와 같은 Exception이 발생하는 이슈입니다.

 

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported]

 


원인

해당 코드에서는 객체를 JSON 형식으로 전송하려고 시도하고 있는 반면, 요청의 콘텐츠 타입이 'application/x-www-form-urlencoded'로 설정되어 있는 것이 원인입니다.

 

RestAPI의 경우 보통 JSON 타입으로 request, response를 하게 됩니다. 그래서 당연히 'application/json' 타입을 Content-Type으로 사용한다고 생각했는데, 그렇지 않다는 걸 알게 되었습니다.

HTML FORM 태그를 사용하여 POST 방식으로 요청하거나

jQuery의 ajax 또는 React의 axios 등의 요청을 할 때 default Contenty-Type은 'application/json' 가 아닌 'application/x-www-form-urlencoded' 입니다.

 

따라서 해결 방법은 요청의 콘텐츠 타입을 'application/x-www-form-urlencoded'로 변경하거나, 요청을 JSON 형식으로 전송하도록 수정하는 것입니다.

 


해결방법

1. 요청의 콘텐츠 타입을 'application/x-www-form-urlencoded'로 변경하는 방법

axios.post('http://localhost:8082/api/v1/auth/n/register', new URLSearchParams({
    userId: user.userId,
    password: user.password
}))


이 방법은 URLSearchParams를 사용하여 요청 본문을 'application/x-www-form-urlencoded' 형식으로 만들어서 전송합니다.

 


2. 요청을 JSON 형식으로 전송하는 방법

axios.post('<http://localhost:8082/api/v1/auth/n/register>', {
    userId: user.userId,
    password: user.password
}, {
    headers: {
        'Content-Type': 'application/json'
    }
})

 

이 방법은 요청의 본문에 JSON 형식의 데이터를 전송하고, 'Content-Type' 헤더를 'application/json'으로 설정하여 서버에게 JSON 형식의 데이터를 전송한다고 알려줍니다.

 

만약 서버가 'application/x-www-form-urlencoded' 형식을 기대한다면 첫 번째 방법을, JSON 형식을 기대한다면 두 번째 방법을 사용하면 됩니다.

 


해결

저의 경우에는 두번째 방법을 선택하여 해결했습니다!

// 회원가입
    let register = () => {
        axios.post('http://localhost:8082/api/v1/auth/n/register', {
            userId: user.userId,
            password: user.password
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then((res) => {
        
            // 회원가입 성공
            alert("회원가입이 완료되었습니다!");
            console.log("Response:", res.data);
        })
        .catch((error) => {
            // 회원가입 실패
            //alert("회원가입에 실패했습니다. 다시 확인해주세요.");
            //console.log("Error:", error);
        });
    }

 

해당 오류는 해결되었는데

다른 오류가 또 기다리고 있네요..^^

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함