| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- import axios from 'axios'
- // Axios 인스턴스 생성
- const createApiClient = () => {
- const config = useRuntimeConfig()
- const apiBase = config.public.apiBase || 'http://localhost'
-
- const client = axios.create({
- baseURL: apiBase,
- timeout: 10000,
- headers: {
- 'Content-Type': 'application/json',
- 'X-Requested-With': 'XMLHttpRequest'
- }
- })
- // 요청 인터셉터
- client.interceptors.request.use(
- (config) => {
- console.log('API Request:', config.method?.toUpperCase(), config.url)
- return config
- },
- (error) => {
- return Promise.reject(error)
- }
- )
- // 응답 인터셉터
- client.interceptors.response.use(
- (response) => {
- return response
- },
- (error) => {
- console.error('API Error:', error.response?.status, error.response?.data)
- return Promise.reject(error)
- }
- )
- return client
- }
- // API 클라이언트 싱글톤
- let apiClient = null
- const getApiClient = () => {
- if (!apiClient) {
- apiClient = createApiClient()
- }
- return apiClient
- }
- // 글로벌 API 메서드들
- export const get = async (url, params = {}) => {
- try {
- const client = getApiClient()
- const response = await client.get(url, { params })
- return response.data
- } catch (error) {
- throw error
- }
- }
- export const post = async (url, data = {}) => {
- try {
- const client = getApiClient()
- const response = await client.post(url, data)
- return response.data
- } catch (error) {
- throw error
- }
- }
- export const postForm = async (url, data = {}) => {
- try {
- const client = getApiClient()
- const formData = new FormData()
- Object.keys(data).forEach(key => {
- formData.append(key, data[key])
- })
- const response = await client.post(url, formData, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- }
- })
- return response.data
- } catch (error) {
- throw error
- }
- }
- export const put = async (url, data = {}) => {
- try {
- const client = getApiClient()
- const response = await client.put(url, data)
- return response.data
- } catch (error) {
- throw error
- }
- }
- export const del = async (url, params = {}) => {
- try {
- const client = getApiClient()
- const response = await client.delete(url, { params })
- return response.data
- } catch (error) {
- throw error
- }
- }
- // 기존 useApi 호환성을 위해 유지
- export const useApi = () => ({
- get,
- post,
- postForm,
- put,
- delete: del
- })
|