본문 바로가기

JavaScript/Ajax, Axios(비동기 통신)

XMLHttpsRequest, axios 로 백엔드 서버에 요청 보내 보기

반응형

vue 파일

<template>
  <div>
    <div>
      Board list:
      <div v-if="loading">Loading...</div>
      <div v-else>APi result : {{ apiRes }}</div>
      <ul>
        <li>
          <router-link to="/b/1">Board 1</router-link>
        </li>
        <li>
          <router-link to="/b/2">Board 2</router-link>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      apiRes: ""
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      //요청하기
      const req = new XMLHttpRequest();

      req.open("GET", "http://localhost:3000/health");

      //클라이언트에서 백엔드서버로 요청을 보낸다
      req.send();

      //로딩이 완료되면
      req.addEventListener("load", () => {
        this.loading = false;
        this.apiRes = {
          status: req.status,
          statusText: req.statusText,
          response: JSON.parse(req.response) //순수 문자열
        };
      });
    }
  }
};
</script>

<style></style>
 fetchData() {
      this.loading = true;
      //요청하기
      const req = new XMLHttpRequest();

      req.open("GET", "http://localhost:3000/health");

      //클라이언트에서 백엔드서버로 요청을 보낸다
      req.send();

      //로딩이 완료되면
      req.addEventListener("load", () => {
        this.loading = false;
        this.apiRes = {
          status: req.status,
          statusText: req.statusText,
          response: JSON.parse(req.response) //순수 문자열
        };
      });
    }

XMLHttpRequest(XHR) 객체는 서버와 상호작용하기 위하여 사용됩니다.

페이지의 새로고침 없이도 URL로 부터 데이터를 받아 올수 있으며 비동기 통신을 위해 활용한다.

 

ajax, axios를 사용하기 전에 요청의 근본이 되는 XMLHttpRequest이다

 

간단하게

status 는 상태( 200, 404 등 상태)

statusText 는 응답에 대한 text(성공시 OK, 실패시 null)

 

response 는 응답에 대한 요청값 반환(문자열로 리턴되기때문에 JSON.parse로 json화 시킨다)

 

 

다음은 axios를 활용해 요청을 보내보겠다.

axios는 XMLHttpRequest를 조금더 편하게 요청을 보낼수 있는 라이브러리이다,

Promise 상태로 return을 해준다

https://github.com/axios/axios

 

axios/axios

Promise based HTTP client for the browser and node.js - axios/axios

github.com

 

<template>
  <div>
    <div>
      Board list:
      <div v-if="loading">Loading...</div>
      <div v-else>APi result : {{ apiRes }}</div>
      <div v-if="error">
        <pre>{{ error }}</pre>
      </div>
      <ul>
        <li>
          <router-link to="/b/1">Board 1</router-link>
        </li>
        <li>
          <router-link to="/b/2">Board 2</router-link>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      loading: false,
      apiRes: "",
      error: ""
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      axios
        .get("http://localhost:3000/health")
        .then(res => {
          console.log(res);
          this.apiRes = res.data;
        })
        .catch(error => {
          console.log(error);
          this.error = error.response.data;
        })
        .finally(() => {
          this.loading = false;
        });

    }
  }
};
</script>

<style></style>

결과는 동일하다

 

반응형

'JavaScript > Ajax, Axios(비동기 통신)' 카테고리의 다른 글

axios 모듈화하기  (0) 2020.03.21
json < - > xml간 연동  (0) 2020.01.22
json <-> ajax간 연동  (0) 2020.01.22
jsp < - > ajax간 데이터 연동  (0) 2020.01.22