프론트/JS

5. 웹 요청을 위한 JS(axios)

초코chip 2024. 10. 28. 14:22

들어가며..

  • JavaScript에서 웹 요청을 보내는 방법 중 하나는 Axios 라이브러리를 사용하는 것
  • Axios는 간결하고 사용이 쉬운 API를 제공하여 비동기 HTTP 요청을 처리하는 데 널리 사용
  • Axios를 통해 서버로 데이터를 보내거나 받아올 수 있으며, AJAX 호출을 더욱 쉽게 구현할 수 있음

 

Async/Await 방식으로 Axios를 사용

요청 보내기

async function fetchData() {
  try {
    const response = await axios.get("https://api.example.com/data");
    const response = await axios.post("https://api.example.com/data", {
      name: "홍길동",
      age: 30
    });
    
    console.log("데이터 가져오기 성공:", response.data);  // 응답 데이터에 접근
  } catch (error) {
    console.error("데이터 가져오기 실패:", error);
  }
}

 

 

가져온 데이터를 속성을 통해 접근하기

  • Axios로 가져온 데이터는 기본적으로 response.data에 저장
  • 에를 들어, 서버 응답 데이터가 아래와 같은 JSON 구조로 되어있다면,

 

 

실전 사용

  1. 비동기 함수를 정의
    •  필요에 따라 데이터를 첨부하여 서버에 전송
    • 응답을 받은 후에는 HTML 요소에 동적으로 데이터를 반영
  2. 비동기 함수와 이벤트 핸들러 연결하기
<button id="fetchButton">데이터 가져오기</button>
<div id="result">여기에 결과가 표시됩니다.</div>
// 1. 비동기 함수 정의
async function fetchData() {
  try {
  	//1-1. 요청 보내기
    const response = await axios.get("https://api.example.com/data");
    
    //1-2. 응답 데이터 반영하기
    const data = response.data;
    document.getElementById("result").textContent = `데이터: ${data.value}`;
    
  } catch (error) {
    console.error("데이터 가져오기 실패:", error);
  }
}

// 2. 버튼에 이벤트 핸들러 연결
const button = document.getElementById("fetchButton");
button.addEventListener("click", fetchData);