비동기 방식
- 비동기 방식은 웹페이지를 리로드 하지 않아도 데이터를 불러와주는 방식
- 결과가 주어지는데 시간이 걸리지만 그 시간 동안에는 다른작업을 병행할 수 있다는 장점과 자원을 효율적으로 사용
npm install axios
import axios from "axios";
axios의 대표적 Request method
GET : axios.get(url[, config])
POST : axios.post(url, data[, config])
PUT : axios.put(url, data[, config])
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]])
입력한 url이 존재하는 자원에 요청을 보냄
axios.get(url,[,config])
GET방식은 서버에서 어떤 데이터를 가져와서 보여줄것인가를 정하는 용도.
주소에 있는 쿼리스트링을 활용해 정보를 전달하는 것이고 GET 메서드는 값이나 상태등을 직접 바꿀수 없음.
// 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);
}
}
새로운 리소스를 생성(create)할 때 사용
axios.post("url주소",{ data객체 },[,config])
POST 메서드의 두 번째 인자는 본문으로 보낼 데이터를 설정한 객체 리터럴을 전달
axios.post("url", {
firstName: 'Lee',
lastName: 'choI'
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류발생시 실행
})
데이터베이스에 저장된 내용을 갱신(수정)하는 목적으로 사용
axios.put(url[, data[, config]])
axios.put("url", {
username: "",
password: ""
})
.then(function (response) {
// response
}).catch(function (error) {
// 오류발생시 실행
})
서버 내부적으로 get -> post 과정을 거치기 때문에 post 메서드와 비슷한 형태
데이터베이스에 저장된 내용을 삭제하는 목적으로 사용
axios.delete(url,[,config]);
axios.delete('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
https://levelup.gitconnected.com/react-custom-hook-useaxios-689fe5a12045