Axios는 JavaScript 라이브러리 중 하나인 Fetch api와 같은 비동기 통신 라이브러리
React ⇒ Axios를 더 많이 사용
특징 : 요청과 응답 모두 JSON 형식으로 자동 변환시켜준다!
const axios = require(`axios`)
// ID로 사용자 요청
axios
.get('/user?ID=12345')
// 응답(성공)
.then(function(response){
console.log(response);
})
// 응답(실패)
.catch(function(error) {
console.log(error);
})
// 응답 (항상 실행)
.then(function(){
// ...
})
axios만을 이용하여 api호출을 하는 경우, 바로 응답이 오지 않기 때문에 일반적으로 비동기 방식을 이용함!
async function getUser(){
try{
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch(error){
console.error(error);
}
}
const axios_get = () => {
axios.get("http://localhost:8080/get") //url
.then((response) => { //통신 성공 시
console.log(response);
})
.catch((error) => { //통신 실패 시
console.log(error);
})
}
const axios_post = () => {
const data = {
name : 'name',
age: 23
}
axios.post("http://localhost:8080/post", data)
.then((response => {
console.log(response)
})
.catch((error) => {
console.log(error);
})
}
const axios_put = () => {
const data = {
age: 25
}
axios.put("http://localhost:8080/put", data)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
const axios_delete = () => {
axios.delete("http://localhost:8080/delete")
}
// DELETE 요청의 두 번째 인자에 data: {} atrribute를 넣어주면 된다.
const axios_delete = () => {
axios.delete("http://localhost:8080/delete",
{
data: {
postId: ...
commentId: ...
}
});
}