ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Axios 기초 배우기 #2 (GET 방식으로 통신하기)
    front-end/Vue.js 2022. 2. 23. 10:13
    728x90

    실제로 axios를 사용하여 이메일과 패스워드를 입력하고 서버와 통신해보겠다.

     

     

     

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

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

    github.com

     

    axios의 github페이지에 사용 예제들이 있다.

     

     

     

    src/views/Login.vue

    <template>
      <v-container fill-height style="max-width:450px;">
        <v-layout align-center row wrap>
          <v-flex xs12>
            <v-alert type="error" :value="isLoginError">
              아이디와 비밀번호를 확인하세요
            </v-alert>
            <v-alert type="success" :value="isLogin">
              로그인 성공
            </v-alert>
            <v-card>
              <v-toolbar flat color="blue-grey lighten-5">
                <v-toolbar-title>로그인</v-toolbar-title>
              </v-toolbar>
              <div class="pa-3">
                <v-text-field v-model="email" label="이메일을 입력하세요">
                </v-text-field>
                <v-text-field
                  v-model="password"
                  type="password"
                  label="패스워드를 입력하세요"
                >
                </v-text-field>
                <v-btn
                  block
                  large
                  depressed
                  color="primary"
                  @click="login({ email, password })"
                  >로그인</v-btn
                >
                <v-btn @click="test">테스트</v-btn>
              </div>
            </v-card>
          </v-flex>
        </v-layout>
      </v-container>
    </template>
    \
    <script>
    import { mapState, mapActions } from "vuex";
    import axios from "axios";
    
    export default {
      data() {
        return {
          email: null,
          password: null,
        };
      },
      computed: {
        ...mapState(["isLogin", "isLoginError"]),
      },
      methods: {
        ...mapActions(["login"]),
        test() {
          axios
            .get("/user?ID=12345")
            .then(function(response) {
              // handle success
              console.log(response);
            })
            .catch(function(error) {
              // handle error
              console.log(error);
            })
            .then(function() {
              // always executed
            });
        },
      },
    };
    </script>
    로그인 버튼 밑에 test 버튼을 하나 만들어준다.
    axios예제를 그대로 가져왔을 때 문제점이 있다.
    response로 받아온 token 등은 vue에서 사용할 필요가 있는데, function 함수를 사용했을 때 this를 쓰면 Vue인스턴스가 아닌 function의 내부를 가리키게 된다.
    이는 ES6의 arrow 함수로 보안할 수 있다.

     

    methods: {
        ...mapActions(["login"]),
        test() {
          axios
            .get("/https://reqres.in/api/users?page=2")
            .then(res => {
              // handle success
              console.log(res);
            })
            .catch(err => {
              // handle error
              console.log(err);
            })
            .then(() => {
              // always executed
            });
        },
      },

     

     

     

    테스트 버튼을 클릭하였을 때 AJAX로 데이터를 받아와 console에 찍히면 성공이다.

    서버와 통신하여 가져오기 때문에 잠깐의 텀이 있을 수 있다.

     

     

     

     

     

    axios의 github페이지에 GET 방식을 사용할 때 Response Schema에 대한 정보를 확인 할 수 있다.

     

    data: 서버에서 제공된 데이터가 오브젝트 형식으로 보내준다.
    status: 서버 통신이 어떻게 되었는지 HTTP status 코드넘버를 확인할 수 있다.
             (HTTP 상태 코드 등을 검색하면 상세한 코드넘버를 확인할 수 있다.)
    statusText: status의 상태를 메세지로 보내준다.
    headers: 보안상 중요한 데이터들을 담아 보내준다. 일반적인 데이터는 body의 형식으로 data {} 안에 담겨있다.
    config: 요청과 응답에 대한 형식이 적혀있다.
    request: 요청에 대한 전반적인 내용들이 적혀있다.

     

     

     

     

    test() {
          axios
            .get("https://reqres.in/api/users?page=2")
            .then((res) => {
              // handle success
              console.log(res);
            })
            .catch((err) => {
              // handle error
              console.log(err);
            })
            .then(() => {
              // always executed
              console.log("test");
            });
        },
    then.catch.then으로 작성하게 되면 언제나 뒤쪽의 then은 실행된다.

     

    통신에 성공했을 때도, 잘못된 주소를 요청했을 때도 console.log("test")는 실행된다.

    728x90

    댓글

Designed by Tistory.