공부용

[vue.js] 7. axios 본문

공부용/vue.js

[vue.js] 7. axios

고딕짱! 2022. 2. 22. 13:12

0. axios

Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코드베이스로 브라우저와 node.js에서 실행할 수 있습니다). 서버 사이드에서는 네이티브 node.js의 http 모듈을 사용하고, 클라이언트(브라우저)에서는 XMLHttpRequests를 사용합니다.

 

쉽게 말해서 백엔드 데이터를 프론트에 가져온다.. 라는것으로 정의할 수 있다!

 

1. 설치

npm install --save axios

 

 

2. 코드

./src/view/axios.vue

<template>
  <table>
    <thead>
      <tr>
        <td>번호</td>
        <td>제목</td>
        <td>작성자</td>
        <td>날짜</td>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(board) in boardList" :key="board.id">
        <td>{{board.id}}</td>
        <td>{{board.title}}</td>
        <td>{{board.writer}}</td>
        <td>{{board.writeDate}}</td>
      </tr>
    </tbody>
  </table>
  <button @click="foo">button</button>
</template>

<style scoped>
table, tr, td, th {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>

 

<script>
  import axios from 'axios';

  const HOST = "http://localhost:3001/api/board";
  let url = HOST+"/list";

  export default {
    data() {
      return {
        boardList : []
      }
    },
    created() {

    },
    methods: {
      foo() {

        axios.get(url, {params : {page : 1}})
        .then((res) => {
          this.boardList = res.data.board;
          console.log(res.data);
        }).catch((error) => {
          console.log(error);
        });

      }
    }

  }
</script>

 

button을 누르면 foo라는 함수가 실행된다.

틀은 axios.get / axios.post / axios.update / axios.delete가 있다.

update랑 delete는 써보지 못했다.

 

axios(restapi url, parameter).then(res => {}).catch(error => {}};

기본틀이고 데이터를 성공적으로 가져오면 res에 저장되어 있다.

 

restapi data

 

가져오기 전
가져온 후

 

 

백엔드 api는 보통 스프링,스프링부트(java) / express (javascript) / 플라스크?(파이썬) 대표적으로 알고 있다.

플라스크는 잘 몰르지만, 이 데이터는 가볍게 제작하기 위해 express로 구성되어있다.

'공부용 > vue.js' 카테고리의 다른 글

[vue.js] 6. mixins  (0) 2022.02.21
[vue.js] 5. vuex  (0) 2022.02.21
[vue.js] 4. props와 emit  (0) 2022.02.21
[vue.js] 3-2 v-if 와 v-on  (0) 2022.02.16
[vue.js] 3-1. vue 템플릿 문법 및 v-for  (0) 2022.02.16
Comments