7주차 사전과제
: Promise, Fetch API, Axios 참고문서 참고해서 공부하고 정리하기
라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리이다.
백엔드랑 프론트엔드간의 통신을 쉽게하기 위해 Ajax와 더불어 사용한다.
$ yarn add axios
axios({
url: '서버주소',
method: 'GET', // 디폴트값
data: {
foo: 'diary'
},
...,
});
이 밖에도 headers, params 등 다양한 요청파라미터가 존재한다.
클라이언트가 웹서버에게 사용자 요청의 목적/종류를 알린다.
axios.get(url)
GET은 URL 주소에 있는 쿼리스트링을 활용하여 정보를 전달한다.
import axios from 'axios';
axios.get(url)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
JSON 형태로 res 객체의 data를 받아온다.
응답객체(res)에는 status 정보와 data 정보 등이 담겨있다.
axios.post(url, data객체)
두 번째 인자로는 본문으로 보낼 데이터를 설정한 객체를 전달한다.
POST를 사용하면 GET과 달리 주소창에 쿼리스트링이 남지 않기 때문에 GET보다 안전하다.
따라서 로그인, 회원가입 등 사용자가 생성한 파일을 서버에다가 업로드할 때 사용한다.
axios.post(url, {
fistName: "",
lastName: ""
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
then() 으로 post가 성공했을 때 res 객체를 받아와서 data를 추출하고,
실패했을 경우에는 catch()로 에러(err)를 실행한다.
axios.put(url, data객체)
서버에 있는 데이터베이스에 저장되어 있는 내용을 갱신(수정)하는 목적으로 사용된다.
axios.put(url, {
username: "",
password: ""
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
axios.delete(url)
서버에 있는 데이터베이스의 내용을 삭제하는 것이 주목적이기 때문에 두 번째 인자를 아예 전달하지 않는다.
axios.delete(url)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
편의를 위해 지원되는 모든 요청 메서드에 별칭이 제공된다.
axios.get(url[, config]) //GET
axios.post(url[, data[, config]]) //POST
axios.put(url[, data[, config]) //PUT
axios.delete(url[, config]) //DELETE
axios.request(config)
axios.head(url[, config])
axios.potions(url[, config])
별칭 메서드를 사용하면 설정(config)에서 url
, method
및 data
속성을 지정할 필요가 없다.