1. Axios란
Javascript의 HTTP 클라이언트 라이브러리로 대부분 브라우저와 Node.js 환경에서 모두 사용한다.
axios는 비동기 HTTP 요청을 보내고 응답을 처리하는 기능을 제공하여 웹 애플리케이션에서 서버와의 데이터 통신을 간편하게 처리할 수 있도록 도와준다.
Spring Framework에서 AJAX를 사용한 것과 비슷하다.
2. Axios 사용법
https://axios-http.com/kr/docs/intro
시작하기 | Axios Docs
시작하기 브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리 Axios란? Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코
axios-http.com
에서 head 태그에 jsDelivr CDN을 사용해서 붙여도 되고 직접 파일을 받아서 사용해도 된다.
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
3. 응용
만약 Axios로 Spring boot 환경에서 로그인처리를 한다고 하면
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<th:block th:replace="component/config :: config"></th:block>
</head>
<style>
input {
display: block;
}
label {
display: block;
}
</style>
<body>
<div th:replace="component/header :: header"></div>
<div th:replace="component/nav :: nav"></div>
<label for="member-email">이메일
<input type="text" id="member-email" name="memberEmail">
</label>
<label for="member-password">비밀번호
<input type="text" id="member-password" name="memberPassword">
</label>
<input type="button" value="로그인" onclick="login()">
<input type="submit" value="뒤로" onclick="back()">
<div th:replace="component/footer :: footer"></div>
</body>
<script>
const back = () => {
history.back();
}
const login = () => {
const email = document.querySelector('input[name="memberEmail"]').value;
const password = document.querySelector('input[name="memberPassword"]').value;
axios({
method: "post",
url: "/login/axios",
data: {
memberEmail: email,
memberPassword: password
}
}).then(res => {
console.log("res", res);
}).catch(err => {
console.log("err", err);
});
}
</script>
</html>
이메일과 패스워드를 input 태그로 입력받고 로그인 버튼을 누르면 login() 함수가 실행되어 axios가 실행되게 된다.
기본적인 틀은 AJAX와 같고 then은 성공 , catch는 예외처리이다.
@PostMapping("/login/axios")
public ResponseEntity memberLogin(@RequestBody MemberDTO memberDTO, HttpSession session) throws Exception {
memberService.loginAxios(memberDTO);
session.setAttribute("loginEmail",memberDTO.getMemberEmail());
return new ResponseEntity<>(HttpStatus.OK);
}
컨트롤러로 값을 전달받아 RequestBody로 MemberDTO 객체로 값을 전달받아서 Service로 전달 , 예외처리는 Service에서 판단한다.
public void loginAxios(MemberDTO memberDTO) {
memberRepository.findByMemberEmailAndMemberPassword(memberDTO.getMemberEmail(),memberDTO.getMemberPassword())
.orElseThrow(() -> new NoSuchElementException("이메일 또는 비밀번호가 틀립니다"));
}
orElseThrow = optional에 값이 없으면 예외선택이다.
메소드에 .으로 메소드를 이어가는 것을 chaining method ( 체이닝 메소드 ) 이라고 한다.
결국 로그인이 실패( 틀린다면 ) orElseThrow의 메소드로 "이메일 또는 비밀번호가 틀립니다" 라는 예외처리로 진행되는 것이다.
여기서 판단되므로 Controller에서 따로 예외처리를 하지 않고 HttpStatus.OK 만 있는 것이다.
'Spring > Spring boot icia 70일차' 카테고리의 다른 글
| Spring boot Rest.api , EndPoint Test (0) | 2023.06.01 |
|---|---|
| Spring boot css나 script 파일화시키기 (0) | 2023.06.01 |