[Javascript]Axios란?
✏️ Axios에 대해 알아보자
Axios는 웹 브라우저와 Node.js 통신을 위한 Promise 기반의 HTTP 요청 처리를 위한 라이브러리이다.
비동기 통신으로 인해 프론트엔드와 백엔드 간 통신을 쉽게 할 수 있다!! like Ajax
자바스크립트에서 동기가 아닌 비동기 처리를 위해 Axios나 Ajax를 사용해주는 것이다
****Promise란?
Promise는 자바스크립트 ES6에서 비동기 처리를 위해 주로 사용되는 객체
****Ajax란?
비동기 자바스크립트란 의미로 Asynchronous JavaScript and XML의 약자이다.
Ajax는 브라우저에 있는 XMLHttpRequest 객체를 이용하여 화면 전체를 새로 고침 하지 않고 변경된 일부 데이터만 로드하는 비동기 처리가 가능!!! Axios는 Ajax와 유사하다.
❓언제 Axios를 사용할까
비동기 통신을 위하여!
API를 이용한 통신을 할 때 주로 사용한다!
⚔️ Fetch vs Axios
Fetch와 Axios둘 다 HTTP 요청을 처리하기 위한 자바스크립트 라이브러리이다. But! 몇 가지 차이점이 있다.
Fetch | Axios | |
자바스크립트 내장 유무 | 내장 ㅇ => 별도의 import나 설치 필요 x |
내장 x => 별도의 설치 필요 |
브라우저 호환 | Fetch는 일부 예전의 인터넷 익스플로러 버전에서 지원하지 않는 경우있음 | 상대적으로 Fetch보다는 호환성 뛰어남 |
JSON 자동 변환 기능 | x | ㅇ |
응답 시간 초과 설정 기능 | x | ㅇ |
=> 설치하는 번거로움이 있지만 Axios를 사용하는 것이 좋아보임ㅇㅇ
(정답은 아님)
🐹 How to Axios
이 두 스크립트를 추가해주면 axios를 사용할 수 있다!!
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Axios와 CRUD!
C: Create - POST
axios.post(url, data 객체)
새로운 리소스를 생성할 때 사용
- post 메서드의 두 번째 인자는 본문으로 보낼 데이터를 설정한 객체 리터럴을 전달
- 로그인, 회원가입 등 사용자가 생성한 파일을 서버에다가 업로드할때 POST 사용
< 로그인 예시를 통한 코드 >
HTML 파일
(이메일 비번 그대로 입력해야 post 성공함)
"email": "eve.holt@reqres.in",
"password": "cityslicka"
<body>
<div>
<input type="email" placeholder="email을 입력해주세용" id="email" value="" >
</div>
<div>
<input type="password" placeholder="비밀번호를 입력해주세용" id="pw" value="">
</div>
<input type="button" onclick='onLoggin()' value="로그인">
</body>
JS 파일
function onLoggin(){
const email = document.getElementById("email");
const password = document.getElementById('pw')
axios({
method:"POST",
url: 'https://reqres.in/api/login',
data:{
"email": email.value,
"password": password.value
}
}).then((res)=>{
console.log(res);
}).catch(error=>{
console.log(error);
throw new Error(error);
});
}
}
R: Read - GET
axios.get(url)
입력한 url에 존재하는 자원을 요청!
예제 코드
import axios from 'axios';
axios.get('https://my-json-server.typicode.com/zofqofhtltm8015/fs/user').then((Response)=>{
console.log(Response.data);
}).catch((Error)=>{
console.log(Error);
})
[
{ id: 1, pw: '1234', name: 'JUST' },
{ id: 2, pw: '1234', name: 'DO' },
{ id: 3, pw: '1234', name: 'IT' }
]
Json 형태로 결과 받아옴
U: Update - PUT
axios.put(url, data 객체)
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신하는 목적으로 사용
D:Delete - DELETE
axios.delete(url)
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용
예제코드
axios.delete("/thisisExample/list/30").then(function(response){
console.log(response);
}).catch(function(ex){
throw new Error(ex)
}