Spring boot
31. 비동기 통신 사용해보기 (Fatch 함수 사용)
앵즌
2024. 9. 2. 22:48
Fatch 함수 사용 예시
https://jsonplaceholder.typicode.com/guide/
JSONPlaceholder - Guide
Guide Below you'll find examples using Fetch API but you can JSONPlaceholder with any other language. You can copy paste the code in your browser console to quickly test JSONPlaceholder. Getting a resource fetch('https://jsonplaceholder.typicode.com/posts/
jsonplaceholder.typicode.com
package com.tenco.bank.api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.tenco.bank.service.UserService;
import lombok.RequiredArgsConstructor;
@RestController
@RequestMapping("/api-user")
@RequiredArgsConstructor
public class UserRestController {
// DI 처리
private final UserService userService;
// 주소
// http:localhost:8080/api-user/check-username?username=홍길동
@GetMapping("/check-username")
public boolean checkName(@RequestParam(name ="username") String username) {
boolean isUse = userService.searchUsername(username) == null ? true : false;
return isUse;
}
}
resource/home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<button type="button"> 중복 검사 </button>
<div id="result"></div>
<script type="text/javascript">
const btn = document.querySelector("button");
const username = "길동";
const resultElement = document.querySelector("#result");
btn.addEventListener("click", function() {
// 비동기 통신(AJAX) - Fetch 함수 사용(GET 방식)
fetch(`http://localhost:8080/api-user/check-username?username=${username}`)
.then(response => response.json()) // 응답을 JSON 형식으로 반환
.then(isUse => {
console.log("결과 확인 ", isUse);
if(isUse) {
resultElement.textContent = "사용 가능";
} else {
resultElement.textContent = "중복된 이름입니다";
}
})
.catch( error => {
console.log("error ", error);
resultElement.textContent = "잘못된 요청입니다.";
});
});
</script>
</body>
</html>