클라이언트와 서버와 JSON을 주고 받는 방법에 대해 정리해보겠습니다.
JS의 Fetch API를 통해 JSON 형태로 데이터를 전달하는 방법입니다.
function duplicatedMemberCheck() {
const data = { "userId" : document.getElementById("userId").value};
fetch('/members/duplicatedMemberCheck',
{
method : 'post',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(data)
})
.then((response) => {
return response.json();
}).then((json) => {
if(json.result == false){
// ...
}
else{
// ...
}
})
}
클라이언트에서 데이터를 JSON으로 전달하고, JSON 형태로 받아서 처리하는 예시입니다.
(1) const data = { ... }
전송할 데이터를 JS에서 직접 JSON으로 생성
(2) fetch heards, body
headers에 content-type이 JSON 임을 표시해주고, body에 JSON.stringify를 이용하여 전달
response.json() 으로 JSON을 얻은 후 사용
@ResponseBody
@PostMapping("/members/duplicatedMemberCheck")
public String duplicateMemberCheck(HttpServletRequest httpServletRequest) throws IOException {
// 1. Request의 body를 읽기
ServletInputStream inputStream = httpServletRequest.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
inputStream.close();
// 2. ObjectMapper를 통해 JAVA 변수로 읽어오기
Map<String, Object> json = new ObjectMapper().readValue(messageBody, HashMap.class);
String userId = (String)json.get("userId");
Boolean result = memberService.checkUserIdDuplication(userId);
// 3. 다시 JSONObject를 생성한 후 전달할 값을 put
JSONObject response = new JSONObject();
response.put("result", result);
// 4. JSONOBject.toString() 을 이용하여 JSON 형태의 문자열로 response 전달
return response.toString();
}