Axois는 부라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리이다.
쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용한다.
이미 자바스크립트에는 fetch API가 있지만, 프레임워크에서 ajax를 구현할 때 axios를 쓰는 편이다.
라이브러리 설치
axios : 서드파티 라이브러리로 설치가 필요
fetch : 현재 브라우저에 빌트인이라 설치가 필요없음
보호
axois : XSRF 보호를 해준다.
fetch : 별도 보호 없음
속성
axois : data 속성을 사용
fetch : body 속성을 사용
속성 특징
axois : data는 object를 포함한다.
fetch : body는 문자열화 되어있다.
응답 성공
axois : status가 200이고 statusText가 'OK'이면 성공이다.
fetch : 응답객체가 ok 속성을 포함하면 성공이다.
데이터 형식
axois : 자동으로 JSON데이터 형식으로 변환된다.
fetch : .json()메서드를 사용해야 한다.
요청 취소
axois : 요청을 취소할 수 있고 타임아웃을 걸 수 있다.
fetch : 해당 기능 존재하지 않음
요청 가로채기
axois : HTTP 요청을 가로챌수 있음
fetch : 기본적으로 제공하지 않음
다운로드
axois : download 진행에 대해 기본적인 지원을 함
fetch : 지원하지 않음
브라우저 지원
axois : 좀 더 많은 브라우저에 지원됨
fetch : Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+이상에 지원
별도의 설치가 필요하다는 단점이 있지만 그것을 커버할 만한 fetch 보다 많은 기능 지원과 문법이 간소화 된다는 장점이 있다.
따라서, 간단하게 사용할 때는 fetch를 쓰고, 이외의 확장성을 염두해봤을 땐 axios를 쓰면 좋다.
서버에서 axois 설치
npm install axios
클라이언트(html)에서 axios 설치
-> jsDeliver / unpkg CDN 둘중 택
<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({
url: 'https://test/api/cafe/list/today', // 통신할 웹문서
method: 'get', // 통신할 방식
data: { // 인자로 보낼 데이터
foo: 'diary'
}
});
/* axios 파라미터 문법 예시 */
axios({
method: "get", // 통신 방식
url: "www.naver.com", // 서버
headers: {'X-Requested-With': 'XMLHttpRequest'} // 요청 헤더 설정
params: { api_key: "1234", langualge: "en" }, // ?파라미터를 전달
responseType: 'json', // default
maxContentLength: 2000, // http 응답 내용의 max 사이즈
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}, // HTTP응답 상태 코드에 대해 promise의 반환 값이 resolve 또는 reject 할지 지정
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
}, // proxy서버의 hostname과 port를 정의
maxRedirects: 5, // node.js에서 사용되는 리다이렉트 최대치를 지정
httpsAgent: new https.Agent({ keepAlive: true }), // node.js에서 https를 요청을 할때 사용자 정의 agent를 정의
})
.then(function (response) {
// response Action
});
axios를 통해 요청을 서버에게 보내면, 서버에서 처리를하고 다시 데이터를 클라이언트에 응답 하게 된다.
이를 .then으로 함수인자로(response)로 받아 객체에 담진 데이터가 바로 응답 데이터이다.
axios({
method: "get", // 통신 방식
url: "www.naver.com", // 서버
})
.then((res) => {
console.log(response.data)
console.log(response.status)
console.log(response.statusText)
console.log(response.headers)
console.log(response.config)
})
response.data: {}, // 서버가 제공한 응답(데이터)
response.status: 200, // `status`는 서버 응답의 HTTP 상태 코드
response.statusText: 'OK', // `statusText`는 서버 응답으로 부터의 HTTP 상태 메시지
response.headers: {}, // `headers` 서버가 응답 한 헤더는 모든 헤더 이름이 소문자로 제공
response.config: {}, // `config`는 요청에 대해 `axios`에 설정된 구성(config)
response.request: {}
// `request`는 응답을 생성한 요청
// 브라우저: XMLHttpRequest 인스턴스
// Node.js: ClientRequest 인스턴스(리디렉션)
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
get 메서드에서는 2가지의 상황이 존재한다.
1. 단순 데이터(페이지 요청, 지정된 요청) 요청을 수행할 경우
2. 파라미터 데이터를 포함시키는 경우 (사용자 번호에 따른 조회)
const axios = require('axios'); // node.js쓸때 모듈 불러오기
// user에게 할당된 id 값과 함께 요청을 합니다.
axios.get('/user?ID=12345')
.then(function (response) {
// 성공했을 때
console.log(response);
})
.catch(function (error) {
// 에러가 났을 때
console.log(error);
})
.finally(function () {
// 항상 실행되는 함수
});
// 위와는 같지만, 옵션을 주고자 할 때는 이렇게 요청을 합니다.
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
// async/await 를 쓰고 싶다면 async 함수/메소드를 만듭니다.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}```
### 2) axios POST
post 메서드에는 일반적으로 데이터를 Message Body에 포함시켜 보낸다.
위에서 봤던 get 메서드에서 params를 사용한 경우와 비슷하게 수행된다.
// async/await 를 쓰고 싶다면 async 함수/메소드를 만듭니다.
```javascript
axios.post("url", {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류발생시 실행
})
delete 메서드에는 일반적으로 body가 비어있다.
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용한다.
axios.delete('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
하지만 query나 params가 많아져서 헤더에 많은 정보를 담을 수 없을 때는
다음과 같이 두 번째 인자에 data를 추가해줄 수 있다.
axios.delete('/user?ID=12345',{
data: {
post_id: 1,
comment_id: 13,
username: "foo"
}
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신(수정)하는 목적으로 사용된다.
PUT메서드는 서버에 있는 데이터베이스의 내용을 변경하는 것을 주 목적으로 하고 있다.
PUT메서드는 서버 내부적으로 get -> post 과정을 거치기 때문에 post 메서드와 비슷한 형태이다.
axios.put("url", {
username: "",
password: ""
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류발생시 실행
})