[vue-news] API 구현 - axios의 api 함수 구조화

aranpark·2021년 10월 8일
0

vue-news

목록 보기
4/8

💻 axios의 api 함수 구조화


  1. /src/api/index.js 생성
import axios from 'axios';

// 1. HTTP Request & Response와 관련된 기본 설정
const config = {
    baseUrl: 'https://api.hnpwa.com/v0/'
}

// 2. API 함수들을 정리
function fetchNewsList(){
    // return axios.get('https://api.hnpwa.com/v0/news/1.json');
    // return axios.get(config.baseUrl + 'news/1.json');
    return axios.get(`${config.baseUrl}news/1.json`);
}
function fetchAskList(){
    return axios.get(`${config.baseUrl}ask/1.json`)
}
function fetchJobsList(){
    return axios.get(`${config.baseUrl}jobs/1.json`)
}

export {
    fetchNewsList,
    fetchAskList,
    fetchJobsList
}
  1. API 호출 /src/views/NewsView.vue
<template>
  <div>
  	<div v-for="user in users">{{ user }}</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    }
  }
  created() {
    var vm = this;
    // promise 기반 객체
    fetchNewsList()
    .then(function(response){
      console.log(response);
      vm.users = response.data
    })
    .catch(function(error){
      console.log(error);
    })
  },
}
</script>

0개의 댓글