카테고리 없음

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 에러 해결

sungw00 2023. 3. 31. 22:00
728x90

경과

로그인 기능을 구현하기 위해 ajax로 서버에 같은 아이디와 비밀번호를 가진 회원이 있는 지 조회한 후 그 결과를 반환받고자 했다. 그런데 자꾸 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported 에러가 떴다.

검색해봐도 ajax 요청 코드 내부에 json인걸 명시하라는 말밖에 없었는데 나는 json인걸 명시해줬다.

컨트롤러 코드

@PostMapping("/checkUser")
    @ResponseBody
    public String checkUser(@RequestBody HashMap<String, String> userInfo) throws Exception {
        String username = userInfo.get("username");
        String password = userInfo.get("password");
        userService.checkUser(userInfo);
        return "/";
    }

자바스크립트(ajax 요청)

let data = {
    username:username,
    password:password
};

let xhr = new XMLHttpRequest();
xhr.open("POST", "/user/checkUser");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.onload = function() {
    if (xhr.status === 200 || xhr.status === 201) {
        let resp = xhr.responseText;
        alert(resp);
        if (resp.status === 500) {
            alert("에러가 발생했습니다.");
        } else {
            alert("로그인이 완료되었습니다.");
            location.href = "/";
        }
    } else {
        console.log(xhr.responseText);
        alert("Request failed. Status: " + xhr.status);
    }
};
xhr.onerror = function() {
    alert("Request failed. Status: " + xhr.status);
};
xhr.send(JSON.stringify(data));

 

원인

자세한 내용은 다른분이 잘 설명해주셔서 이걸 참고하면 될것같다.

https://ocblog.tistory.com/49

 

Spring / @RequestBody vs @RequestParam 이해하기

컨트롤러에서 데이터를 인자에 할당하는 대표적인 방법으로는 @RequestBody 와 @RequestParam 이 있다. @Controller public class UserController { @PostMapping("/receive") public String age(@RequestParam String name) { System.out.prin

ocblog.tistory.com

 

해결

결국 @RequestBody가 아닌 @RequestParam을 사용하니 데이터가 잘 넘어와지고, 에러도 발생하지 않았다.

 

 

728x90