React Native/프로젝트
axios/fetch
spring_sunshine
2022. 6. 23. 14:47
Axios vs Fetch
- Fetch API는 네트워크 요청을 위해 fetch()라는 메서드를 제공하는 인터페이스이다. 브라우저에 내장되어 있어 따로 설치할 필요가 없다.
- Axios는 서드파티 라이브러리로 CDN, npm, yarn과 같은 패키지 매니저를 통해 설치하여 프로젝트에 추가할 수 있다. 브라우저 혹은 node.js 환경에서 실행할 수 있다.
- 둘 다 모두 promise 기반의 HTTP 클라이언트이다. 이 클라이언트들을 이용하여 네트워크 요청을 하면 resolve 혹은 reject 할 수 있는 promise가 반환된다.
Fetch
- Fetch는 두 개의 인자를 받는다. 첫번째 인자는 가져오고자 하는 리소스의 URL이고, 두번째 인자는 요청의 설정 옵션을 포함하는 객체이며 선택적 인자이다.
두번째 인자로 설정 옵션을 넘기지 않을 경우, 기본적으로 GET 요청을 생성한다.
fetch(url);
설정 옵션을 넘기면, 다음과 같이 요청에 대한 커스텀 설정을 할 수 있다.
fetch(url, {
method: "GET", // 다른 옵션도 가능(POST, PUT, DELETE, ...)
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
});
Axios란?
- Axios는 브라우저, node.js를 위한 Promise API를 활용한 HTTP 비동기 통신 라이브러리이다.
- 백엔드와 프론트엔드의 통신을 쉽게하기 위해 Ajax와 더불어 사용한다.
https://inpa.tistory.com/entry/AXIOS-%F0%9F%93%9A-%EC%84%A4%EC%B9%98-%EC%82%AC%EC%9A%A9
[AXIOS] 📚 axios 설치 & 특징 & 문법 💯 정리
Axios 란? Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리 아다. 쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용한다. 이미 자바스크
inpa.tistory.com
Axios 문법 구성
axios({
url: "https://test/api/cafe/list/today", // 통신할 웹문서
method: "get", // 통신방식
data: { // 인자로 보낼 데이터
foo: 'diary'
}
})
- method: 요청방식 (디폴트: get)
- url: 서버 주소
- headers: 요청 헤더
- data: 요청방식이 'PUT', 'POST', 'PATCH'에 해당하는 경우 body에 보내는 데이터
- params: URL 파라미터 (?key=value로 요청하는 url get 방식을 객체로 표현한 것)
Axios 응답 데이터
- axios를 통해 요청을 서버에게 보내면, 서버에서 처리를 하고 다시 데이터를 클라이언트에 응답하게 된다.
- 이를 .then으로 함수인자로 받아 객체에 담겨진 데이터가 바로 응답 데이터이다.
ajax를 통해 서버로부터 받는 응답 정보는 다음과 같다.
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)
})
{
data: {}, // 서버가 제공한 응답(데이터)
status: 200, // status는 서버 응답의 HTTP 상태코드
statusText: 'OK', // statusText는 서버 응답으로부터의 HTTP 상태 메세지
headers: {}, // headers 서버가 응답한 헤더는 모든 헤더 이름을 소문자로 제공
config: {}, // config는 요청에 대해 axios에 설정된 구성
request: {}
// request는 응답을 생성한 요청
}
Axios 메소드
- GET: axios.get(url[, config])
- POST: axios.post(url, data[, config])
- PUT: axios.put(url, data[, config])
- DELETE: axios.delete(url[, config])
axios GET
- get 메서드에는 크게 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 () {
// 항상 실행
});
// async/await을 쓰고 싶다면 async 함수/메소드 생성
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
}
catch {
console.log(error);
}
}
axios POST
- post 메서드는 일반적으로 데이터를 Message Body에 포함시켜 보낸다.
- 위에서 본 get 메서드에서 params를 사용한 경우와 비슷하게 수행된다.
axios.post("url", {
firstName: 'Fred',
lastName: 'GoldStone'
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류 시 실행
})
axios PUT
- REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신(수정)하는 목적으로 사용된다.
- put 메서드는 서버에 있는 데이터베이스 내용 변경을 주 목적으로 한다.
- put 메서드는 서버 내부적으로 get → post 과정을 거치기 때문에 post 메서드와 비슷한 형태이다.
axios.put("url", {
username: "",
password: ""
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류 시 실행
})
axios DELETE
- delete 메서드는 일반적으로 body가 비어있다.
- REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용한다.
axios.delete('/user?ID=12345')
.then(function (response) {
console.log(response); // success
})
.catch(function (error) {
console.log(error); // error
})
Axios 예제
1-1) GET 요청 수행
const axios = require('axios');
// 지정된 ID를 가진 유저에 대한 요청
axios.get('/user?ID=12345')
.then(function (response) {
// 성공 핸들링
console.log(response);
})
.catch(function (error) {
// 에러 핸들링
console.log(error);
})
.then(function () {
// 항상 실행
});
1-2) GET 요청 수행
// 선택적으로 위의 요청은 다음과 같이 수행될 수도 있음
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// 항상 실행
});
// async/await 사용을 원하면 함수 외부에 'async' 키워드를 추가하자
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
}
catch (error) {
console.error(error);
}
}
2-1) POST 요청 생성
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
2-2) 여러 동시 POST 요청 생성
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissons');
}
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const account = results[0];
const permission = results[1];
});