반응형

개발 상황

axios를 통해서 controller에 통신을 하려던 중 에러가 발생되었다.

더 정확히는, 통신은 되는데 axios에서 보낸 data가 controller에서 찍히지 않았다.

 

문제의 소스는 아래와 같다.

// xx.js
axios({
    url: "/store/getStore",
    method: "get",
    data: { seq: values.seq }
}).then((res) => {
    console.log(res.data);
})

// xx.java
@ResponseBody
@GetMapping("/getStore")
public String getStore(Map<String, Object> param) throws JsonProcessingException {
    System.out.println("getStore");
    Integer seq = (Integer) param.get("seq");
    System.out.println("Received seq: " + seq);

    Map<String, Object> store = storeService.getStore(param);

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(store);
}

 

구글링 중 몇가지 방법을 찾았는데 param을 찍으려면 @RequestBody를 해야한다하였다.

public String getStore(@RequestBody Map<String, Object> param) throws JsonProcessingException {

 

그런데 되지않음...

 

axios에 header를 추가해보라 하였지만 되지않음..

 

마지막에 찾은게 method를 get으로 하지말고 post로 전송하여야 된다는걸 보았다.

 

최종코드는 아래와 같다.

// xx.js
axios({
    url: "/store/getStore",
    method: "post",
    data: { seq: values.seq }
}).then((res) => {
    console.log(res.data);
})

// xx.java
@ResponseBody
@PostMapping("/getStore")
public String getStore(@RequestBody Map<String, Object> param) throws JsonProcessingException {
    System.out.println("getStore");
    Map<String, Object> store = storeService.getStore(param);

    ObjectMapper mapper = new ObjectMapper();
    return mapper.writeValueAsString(store);
}

 

여러가지 이유가 있다.

1. 비동기 통신을 할때 전송 데이터 타입이 context-type이 json이 아닌경우 아래 예시 참고

axios.post(url, formData, { headers: { "Content-Type": `application/json`} }
).then((res) => {
  console.log(res);
})

2. @RequestBody를 잘 적용하였는지 확인

3. 전송 혹은 받는 곳이 get이 아닌 post를 잘 적용되었는지 확인

 

나같은 경우는 2,3을 적용하여서 해결

반응형