안녕하세요 오늘은 Axios로 CRUD를 구현해 보도록 하겠습니다.
지금부터 Axios로 CRUD를 구현해 보도록 하겠습니다.
😎 Axios 선언하기
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>😎 CRUD 구현
Read(읽기) : GET
데이터 리스트를 받아올때는 보통 get방식으로 Http통신을 합니다 axios.get 메소드를 사용하여 get방식으로 통신할수 있습니다
	getUser(id, event){
        axios.get('http://localhost:8080/users/'+id)
          .then((result) => {
                var data = result.data;
                     document.getElementById("userName_update").value = data.name;
                     document.getElementById("userAge_update").value = data.age;
                     document.getElementById("userid_update").value = data.id;
                })
                .catch((error) => {
                     console.log(error);
                 })
                .finally(() => {
                     console.log("finally");
                 })
    }
Create(생성) : POST
데이터를 저장할때는 보통 post방식으로 HTTP통신을 합니다 axios.post 메소드를 사용하여 post방식으로 통신 할수 있습니다
   	insertUser(){
    	var name = document.getElementById("userName").value;
        var age = document.getElementById("userAge").value;
        axios.post('http://localhost:8080/users', {"name" : name, "age" : age})
            .then((result) => {
                  alert("등록되었습니다.")
                  document.getElementById("axiosBody").classList.remove("black-bg");
                  document.getElementById("insertModal").style.display = "none";
                  app.getAllUsers();
             })
             .catch((error) => {
             	  console.log(error);
             })
             .finally(() => {
                  console.log("finally");
             })
   }
Update(생성) : PATCH
데이터를 수정할때는 보통 PATCH방식으로 HTTP통신을 합니다 axios.patch 메소드를 사용하여 PATCH방식으로 통신 할수 있습니다
	updateUser(){
    	var id = document.getElementById("userid_update").value
        var name = document.getElementById("userName_update").value;
        var age = document.getElementById("userAge_update").value;
        axios.patch('http://localhost:8080/users/'+id, {"name" : name, "age" : age})
        	.then((result) => {
            	alert("수정되었습니다.")
                document.getElementById("axiosBody").classList.remove("black-bg");
                document.getElementById("updateModal").style.display = "none";
                app.getAllUsers();
            })
            .catch((error) => {
            	console.log(error);
            })
            .finally(() => {
            	console.log("finally");
            })
   }
Delete(삭제) : DELETE
데이터를 삭제할때는 보통 DELETE방식으로 HTTP통신을 합니다 axios.delete 메소드를 사용하여 DELETE방식으로 통신 할수 있습니다
	deleteUser(id, event){
   		axios.delete('http://localhost:8080/users/'+id)
           	.then((result) => {
               		alert("삭제되었습니다.")
                    this.getAllUsers();
            })
            .catch((error) => {
           		 console.log(error);
            })
            .finally(() => {
                 console.log("finally");
            })
    }
Axios와 통신하는 controller를 구현하였습니다
@Controller
@RequiredArgsConstructor
@RequestMapping("/users")
public class MainApiController {
    private final MainService mainService;
    @ResponseBody
    @GetMapping("")
    public List<UserVO> getAllUsers() throws Exception {
        return mainService.getAllUsers();
    }
    @ResponseBody
    @GetMapping("/{id}")
    public UserVO getUser(@PathVariable("id") String id) throws Exception {
        return mainService.getUser(id);
    }
    @ResponseBody
    @DeleteMapping("/{id}")
    public int deleteUser(@PathVariable("id") String id) throws Exception{
        return mainService.deleteUser(id);
    }
    @ResponseBody
    @PostMapping("")
    public int insertUser(@RequestBody UserVO userVO) throws Exception{
        return mainService.insertUser(userVO);
    }
    @ResponseBody
    @PatchMapping("/{id}")
    public int modifyUser(@PathVariable("id") String id, @RequestBody UserVO userVO) throws Exception{
        return mainService.updateUser(id, userVO);
    }
}
 
구현 결과 정상적으로 동작하는 것을 확인 할수 있었습니다 다음엔 더 재미있는 소재로 찾아뵙도록 하겠습니다 감사합니다.