[WIL]항해 99 5주차 회고록

Dq_q H·2022년 2월 13일
0

Axios

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 Method를 사용하기 위해서는 axios에 .을 붙히며 소문자로 Req Method를 넣어주면 된다.

그리고 해당 메서드의 파라미터에는 API의 주소를 넣는다.

일반적인 axios

일반적으로 우리는 axios의 4가지 기본 메서드를 사용하기 위해 지정해야할 것들이 있다.

4가지 기본 Params

Method
Url
Data (optional)
Params (optional)

이 4가지 방법을 axios에 알려줘야 한다.

axios({
    method: "get",
    url: "url",
    responseType: "type"
}).then(function (response) {
    // response Action
});
 

위와 같이 사용하는 것이 가장 기본적인 axios에 대한 사용법이다.

만약 POST 메서드에서 data를 전송하기 위해서는 url 밑에 data Object를 추가하면 된다.

단축된 axios 메서드

아까 위에서 말 했듯 단축된 axios의 메서드를 사용해서 위의 4가지 기본 파라미터를 생략하거나 간결하게 사용할 수 있다.

axios.get()

get 메서드를 단축된 속성으로 사용하려면 get 메서드를 사용하면 된다.

get 메서드에는 2가지 상황이 크게 존재한다.

단순 데이터(페이지 요청, 지정된 요청) 요청을 수행할 경우
파라미터 데이터를 포함시키는 경우 (사용자 번호에 따른 조회)

2가지 상황에 따라 params: {} 객체가 존재할지 안할지가 결정된다.

단순 데이터를 요청할 경우

// callback 을 사용할 때,
axios.get("url")
    .then(function (response) {
         // response  
    }).catch(function (error) {
        // 오류발생시 실행
    }).then(function() {
        // 항상 실행
    });
    
// async await 함수를 사용할 때, 

try {
	const data = await axios.get("url");
} catch {
	// 오류 발생시 실행
}
 

파라미터 데이터를 포함시키는 경우

axios.get("url", {
      params: {
        id: 123
      }
    })
    .then(function (response) {
         // response  
    }).catch(function (error) {
        // 오류발생시 실행
    }).then(function() {
        // 항상 실행
    });
   
   
// async await 함수를 사용할 때, 

try {
	const data = await axios.get("url", params: { id: 123 });
} catch {
	// 오류 발생시 실행
}
 

axios.post()

post 메서드에는 일반적으로 데이터를 Message Body에 포함시켜 보낸다.

위에서 봤던 get 메서드에서 params를 사용한 경우와 비슷하게 수행된다.

axios.post("url", {
        username: "",
        password: ""
    })
    .then(function (response) {
         // response  
    }).catch(function (error) {
        // 오류발생시 실행
    }).then(function() {
        // 항상 실행
    });
    
// async await 함수를 사용할 때, 

try {
	const data = await axios.post("url");
} catch {
	// 오류 발생시 실행
}

axios.put()

put 메서드는 서버 내부적으로 get -> post 과정을 거치기 때문에 post 메서드와 비슷한 형태이다.

axios.put("url", {
        username: "",
        password: ""
    })
    .then(function (response) {
         // response  
    }).catch(function (error) {
        // 오류발생시 실행
    }).then(function() {
        // 항상 실행
    });
    
// async await 함수를 사용할 때, 

try {
	const data = await axios.put("url", { username: "", password: ""});
} catch {
	// 오류 발생시 실행
}

axios.delete()

delete 메서드에는 일반적으로 body가 비어있다.

그래서 형태는 get과 비슷한 형태를 띄지만 한 번 delete 메서드가 서버에 들어가게 된다면 서버 내에서 삭제 process를 진행하게 된다.

일반적인 delete

axios.delete('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
  
  // async await 함수를 사용할 때, 

try {
	const data = await axios.delete("url");
} catch {
	// 오류 발생시 실행
}

많은 데이터를 요청할 경우

하지만 query나 params가 많아져서 헤더에 많은 정보를 담을 수 없을 때는 다음과 같이 두 번째 인자에 data를 추가해줄 수 있다.

axios.delete('/user?ID=12345',{
    data: {
      post_id: 1,
      comment_id: 13,
      username: "foo"
    }
  })
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

0개의 댓글

관련 채용 정보