[vue.js] Axios로 crud 구현하기

jihun Choi·2023년 9월 11일
0

안녕하세요 오늘은 Axios로 CRUD를 구현해 보도록 하겠습니다.

😎 Axios란?

  • node.js와 브라우저를 위한 Promise 기반 Http 클라이언트 라이브러리입니다
  • Vue에서 권고하는 HTTP 통신 라이브러리 입니다

😎 CRUD란?

  • 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 CRUD 라고 부릅니다.
  1. create(생성) : POST
  2. Read(읽기) : GET
  3. Update(생성) : PATCH
  4. Delete(삭제) : DELETE

지금부터 Axios로 CRUD를 구현해 보도록 하겠습니다.

😎 Axios 선언하기

  • CDM 방식
    html에 axios.min.js를 임포트 시켜주면 됩니다
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

😎 CRUD 구현

  1. 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");
                 })
    }
  1. 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");
             })
   }
  1. 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");
            })
   }
  1. 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");
                })
        }

😎 Controller 구현

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);
    }

}

구현 결과 정상적으로 동작하는 것을 확인 할수 있었습니다 다음엔 더 재미있는 소재로 찾아뵙도록 하겠습니다 감사합니다.

profile
성장을 위해 열심히 노력하는 개발자 입니다

0개의 댓글