AXIOS

설치

npm install axios

객체 정의

방법 1

import axios from "axios";  
  
export default axios.create({  
    baseURL: import.meta.env.VITE_URL,  
    headers:{  
        "Content-type" : "application/json"  
    }  
})

방법2

import axios from 'axios';  
  
const instance = axios.create({  
    baseURL: import.meta.env.VITE_URL,  
    headers: {  
        "Content-Type":"application/json"  
    }  
})  
  
export default instance;

logging

instance.interceptors.request.use(  
    (config) => {  
        console.log('axios.js request : ' , config);  
        return config  
    },  
    (error) => {  
        return Promise.reject(error);  
    }  
);  
instance.interceptors.response.use(  
    (res) => {  
        console.log('axios.js response : ' , res);  
        return res  
    },  
    (error) => {  
        return Promise.reject(error);  
    }  
)  

사용

import axios from "@/plugins/axios";  
import {useWelcomeMessageStore} from "@/stores/welcomeMessageStore"  
  
const message = useWelcomeMessageStore();  
  
const onClick = async()=> {  
  try{  
    await axios.get('/api/hello')  
        .then((response)=>{  
          console.log('data : ' + response.data)  
          message.setWelcomeMessage(response.data)  
        })  
  }catch(e){  
    console.log(e)  
    alert('Error데이터를 불러올 수 없습니다')  
  }  
}

연결문서

댓글남기기