Web
[AXIOS] axios 다루기
ellapk
2022. 8. 21. 14:52
axios 문법 구성
axios({
url: 'https://localhost:1234/api/member', //통신할 웹 문서
member: 'get', //통신 방식
data: {//인자로 보낼 데이터
member : 'james'
}
});
axios 요청(request) 파라미터 옵션
- method : 요청 방식 (get이 디폴트)
- url : 서버 주소
- headers : 요청 헤더
- data : 요청 방식이 'PUT', 'POST', 'PATCH'에 해당하는 경우 body에 보내는 데이터
- params: URL파라미터
axios 응답 데이터
axios를 통해 서버로 요청을 보내면, 서버에서 이를 처리한 후 다시 데이터를 클라이언트에 응답하게 된다.
이를 .then을 통한 함수인자(response)로 받아 객체에 담긴 데이터가 응답 데이터가 된다.
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.config)
console.log(response.request)
})
따라서 ajax를 통해 서버로부터 받는 응답의 정보는 아래와 같음
response.data: {}, //서버가 제공한 응답(데이터)
response.status: 200, //'status'를 통해 서버 응답의 HTTP 상태 코드
response.statusText: 'OK', //'statusText'는 서버 응답으로 부터의 HTTP 상태 메세지
response.config: {}, //'config'는 요청에 대해 'axios'에 대해 설정 된 구성
response.request: {} //'request'는 응답을 생성한 요청
axios GET
1. 단순 데이터 요청
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(){
//항상 실행되는 함수
});
2. 사용자 번호를 지정한 요청
axios.get('/user',{
params: {
ID: 12345
}
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
})
.finally(function(){
//always executed
});
이러면 ID가 12345인 경우의 응답만 돌아오겠지!
추가) async/await를 사용한 요청
async function getUser(){
try{
const response = awiat axios.get('/user?ID=12345');
console.log(response);
} catch(error){
console.error(error);
}
}
axios POST
axios.post("url", {
firstName: 'park',
lastName: 'james'
})
.then(function(response){
//response
}).catch(function(error){
//오류 발생시 실행
})
위에서 GET 메서드 사용시 params를 사용한 경우와 비슷하게 데이터를 message body에 포함시켜 보낸다.
axios DELETE
axios.delete('/user?ID=12345')
.then(function(response){
//handle success
console.log(response);
})
.catch(function(error){
//handle error
console.log(error);
})
REST 기반 API 프로그램에서 DB에 저장되어 있는 내용을 삭제하는 목적으로 사용한다.
DELETE에서도 GET, POST에서 사용한 것과 같이 params 를 활용해 삭제하는 방법도 가능함.
axios PUT
axios.put("url",{
username:"",
password:""
})
.then(function(response){
//response
}).catch(function(error){
//오류 발생 시 실행
})
https://inpa.tistory.com/entry/AXIOS-%F0%9F%93%9A-%EC%84%A4%EC%B9%98-%EC%82%AC%EC%9A%A9