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+이상에 지원 |
-> 위와 같이 axios는 별도의 설치가 필요하다는 단점이 있지만 그것을 커버할 만한 fetch보다 많은 기능지원과 문법이 조금이나마 간소화 된다는 장점이 있다는 것을 볼 수 있습니다.
따라서, 간단하게 사용할때는 fetch를 쓰고, 이외의 확장성을 염두해봤을 땐 axios를 쓰면 좋다고 보면 될 것 같습니다.
npm install axios
axios({
url: 'https://test/api/cafe/list/today', // 통신할 웹문서
method: 'get', // 통신할 방식
data: { // 인자로 보낼 데이터
foo: 'diary'
}
});
axios 요청(request)파라미터 옵션
axios({
method: "get", // 통신 방식
url: "www.naver.com", // 서버
})
.then(function(response) {
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를 편리하게 사용하기 위해 모든 요청 메소드는 ailases가 제공된다.
위 처럼 객체 옵션을 이것저것 주면 가독성이 떨어지고 너저분하니, 함수형으로 재구성하여 나눠논 것으로 이해하면 된다. axios의 Request method에는 대표적으로 다음과 같은 것들이 있다.
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])
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);
}
}
post 메서드에서는 일반적으로 데이터를 Message Body에 포함시켜 보낸다.
위에서 봤던 get 메서드에서 params를 사용한 경우와 비슷하게 수행된다.
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) {
// 오류발생시 실행
})
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);
};
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()
})