[Javascript] Common axios service for reuseability

Zhentiw發表於2024-11-24

It is not good to import axios from each Components or different services, because it will create a new instance of axios everytime.

import axios from "axios";

const apiClient = axios.create({
    baseURL: 'https://my-json-server.typicode.com/Code-Pop/Real-World-Vue-3-New-Syntax',
    withCredentials: false,
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
    }
})
export default {
    getEvents() {
        return apiClient.get('/events')
    }
}

Usage:

<script setup>
import EventCard from '@/components/EventCard.vue'
import { ref, onMounted } from 'vue'
import EventService from '@/services/EventService'

const events = ref(null)
onMounted(async () => {
  EventService.getEvents()
    .then(response => {
      events.value = response.data
    })
    .catch(error => {
      console.error('There was an error!', error)
    })
})

</script>

相關文章