Dev/Spring

[ Spring ] axios로 AJAX 통신 ( + 415 에러코드 & 한글깨짐)

surimi🍥 2021. 3. 5. 15:54
반응형

pom.xml 에 해당 dependency를 추가해야한다.

(이 dependency 없이 AJax 통신을 시도하면 cotroller로 넘어가는 데이터가 null이거나 415 에러가 뜬다.)

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.5</version>
    </dependency>

 

Model

@Data
@Component
public class Member {
    String email;
    String nickname;
    String password;
}

 

JS

    axios({
        method: 'post',
        url: "/register",
        data: {
            'email': email,
            'nickname': nickname,
            'password': pwd
        },
        dataType: 'text'
    })
    .then(function (response){
        console.log(response);
    })
    .catch(function (error){
        console.log(error);
    })

# dataType이 json이어도 된다.

 

 

Controller

    @RequestMapping(value="register", method=RequestMethod.POST)
    @ResponseBody
    public void register(@RequestBody Member member) {
        System.out.println("nick : " + member.getNickname());
        System.out.println("pwd : " + member.getPassword());
        System.out.println("email : " + member.getEmail());
    }
    @RequestMapping(value="register", method=RequestMethod.POST)
    @ResponseBody
    public void register(@RequestBody Map<String, String> map) {
       System.out.println("nick : " + map.get("nickname"));
       System.out.println("pwd : " + map.get("password"));
       System.out.println("email : " + map.get("email"));

    }

 

 

 

 

# 한글이 깨질경우

@RequestMapping(value="register", method=RequestMethod.POST, produces = "application/text; charset=utf8")
    @ResponseBody
    public void register(@RequestBody Map<String, String> map) {
       System.out.println("nick : " + map.get("nickname"));
       System.out.println("pwd : " + map.get("password"));
       System.out.println("email : " + map.get("email"));

    }

Controller에 produces = "application/text; charset=utf8" 추가

 axios({
        method: 'post',
        url: "/register",
        data: array,
        dataType: 'json',
        contentType: "application/json; charset=utf-8;",
    })
    .then(function (response){
        console.log(response);
    })
    .catch(function (error){
        console.log(error);
    })

contentType: "application/json; charset=utf-8;" 추가

반응형