지금까지 몇개의 프로젝트를 하면서 대부분 axios를 사용했다.
fetch를 쓸때도 있지만 axios가 가장 편하고 좋은것 같다.
그런데 사용하다보니 자세하게 알지 못하면서 사용을 해왔던 것 같다.
그래서 다시 한번 알아보려고 한다.
Axios 라이브러리
- axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리 이다.
- 쉽게 말해 백엔드와 프론트엔드의 통신을 쉽게하기 위해 Ajax와 더불어 사용한다.
- 이미 자바스크립트에는 fetch api가 있지만, 프레임워크에서 ajax를 구현할땐 axios를 쓰는 편이다.
Axios 특징
- 운영 환경에 따라 XMLHttpRequest 객체 또는 Node.js의 http api 사용
- Promise API 사용
- 요청과 응답 데이터의 변형
- HTTP 요청 취소
- HTTP 요청과 응답을 JSON 형태로 자동 변경
axios와 fetch를 비교해보면
| axios | fetch |
| 써드파티 라이브러리로 설치가 필요 | 현대 브라우저에 빌트인이라 설치 필요 없음 |
| XSRF 보호를 해준다. | 별도 보호 없음 |
| data 속성을 사용 | body 속성을 사용 |
| data는 object를 포함한다 | body는 문자열화 되어있다 |
| status가 200이고 statusText가 ‘OK’이면 성공이다 | 응답객체가 ok 속성을 포함하면 성공이다 |
| 자동으로 JSON데이터 형식으로 변환된다 | .json()메서드를 사용해야 한다. |
| 요청을 취소할 수 있고 타임아웃을 걸 수 있다. | 해당 기능 존재 하지않음 |
| HTTP 요청을 가로챌수 있음 | 기본적으로 제공하지 않음 |
| download진행에 대해 기본적인 지원을 함 | 지원하지 않음 |
| 좀더 많은 브라우저에 지원됨 | Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+이상에 지원 |
출처: https://inpa.tistory.com/entry/AXIOS-📚-설치-사용 [Inpa Dev 👨💻:티스토리]
위에 표를 보면 굳이 따지만 axios는 별도의 설치가 필요하다는 단점이 있지만 그것을 커버할 만큼 fetch보다 많은 기능 지원과 문법 간소화 등 장점이 있다.
따라서 간단하게 사용할때는 fetch를 사용하고, 이외의 확장성을 염두해봤을 땐 axios를 쓰면 좋다.
Axios 사용법
npm install 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 문법 구성
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 단축 메소드
axios를 편리하게 사용하기 위해 모든 요청 메소드는 aliases가 제공된다.
위에 처럼 하면 가독성이 떨어지고 너저분해 함수형으로 재구성 해서 나눠논 것이라고 이해하면 된다.
대표적으로는
1. GET : axios.get(url[,config])
2. POST : axios.post(url,data[,config])
3. PUT : axios.put(url,data[,config])
4. DELETE : axios.delete(url[,config])
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]])
axios GET
get 메소드는 크게 2가지 상황이 존재한다
1. 단순 데이터 요청을 수행할 경우
2. 파라미터 데이터를 포함시키는 경우 (사용자 번호에 따른 조회)
axios POST
post 메소드는 일반적으로 데이터를 message Body에 포함시켜 보낸다.
axios Delete
delete 메소드는 일반적으로 body가 비어있다.
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용한다.
axios PUT
REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신 하는 목적으로 사용된다.
PUT메소드는 서버에 있는 데이터베이스의 내용을 변경하는 것을 주 목적으로 한다.
put메소드는 서버 내부적으로 get -> post과정을 거치기 때문에 post메소드와 비슷한 형태이다.
다양한 Axios 응용 메소드
axios 동시 요청
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 두개의 요청이 성공했을 때
}));
개인적으로 이거는 처음 알았는데 신기하고 재미있는거 같다.
axios Instance 만들기
custom 속성을 지닌 axios 만의 instance를 만들 수 있다.
//axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
axios로 formdata보내기
const addCustomer = () => {
const url = `/api/customers`;
const formData = new FormData();
formData.append("image", file);
formData.append("name", userName);
formData.append("birthday", birthday);
formData.append("gender", gender);
formData.append("job", job);
const config = {
headers: {
"content-type": "multipart/form-data",
},
};
return axios.post(url, formData, config);
};
원격 이미지 다운 받기 (blob)
const imgurl = 'https://play-lh.googleusercontent.com/hYdIazwJBlPhmN74Yz3m_jU9nA6t02U7ZARfKunt6dauUAB6O3nLHp0v5ypisNt9OJk';
axios({
url: imgurl,
method: 'GET',
responseType: 'blob' // blob 데이터로 이미지 리소스를 받아오게 지정
})
.then((response) => {
const url = URL.createObjectURL(new Blob([response.data])); // blob 데이터를 객체 url로 변환
// 이미지 자동 다운 로직
const link = document.createElement('a');
link.href = url
link.setAttribute('download', `sample.png`)
document.body.appendChild(link)
link.click()
})
axios 에러 핸들링 하기
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // 만일 응답코드가 500일경우 reject()를 반환한다.
}
})
.catch(function (error) {
console.log(error.toJSON());
})
Axios 전역 설정 (Config Defaults)
모든 요청에 적용되는 설정을 default 값을 전역으로 명시할 수 있다.
주로 서버에서 서버로 axios를 사용할때 요청 헤더를 명시하는데 자주 쓰인다.
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// Instance를 만들 때 설정의 default 값을 설정할 수 있다.
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Instance를 만든 후 defalut 값을 수정할 수 있다.
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
instance.defaults.timeout = 2500;'이것저것' 카테고리의 다른 글
| Mixed Content (Next.js) (0) | 2024.04.19 |
|---|---|
| js의 console (0) | 2024.04.14 |
| Zustand 읽어보기 (0) | 2024.03.21 |
| OAuth 2.0 (2) | 2024.03.08 |
| Storybook 1 (1) | 2024.02.27 |