useApi.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import axios from 'axios'
  2. // API Base URL (환경변수 또는 기본값)
  3. const API_BASE_URL = process.env.NUXT_PUBLIC_API_BASE || 'http://gojinaudi.mycafe24.com/api'
  4. // Axios 인스턴스 생성
  5. const apiClient = axios.create({
  6. baseURL: API_BASE_URL,
  7. timeout: 30000,
  8. headers: {
  9. 'Content-Type': 'application/json'
  10. }
  11. })
  12. // Request Interceptor (토큰 자동 추가)
  13. apiClient.interceptors.request.use(
  14. (config) => {
  15. if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {
  16. const token = localStorage.getItem('admin_token')
  17. if (token) {
  18. config.headers.Authorization = `Bearer ${token}`
  19. console.log('[useApi] Request with token:', config.url, token.substring(0, 20) + '...')
  20. } else {
  21. console.log('[useApi] Request without token:', config.url)
  22. }
  23. }
  24. return config
  25. },
  26. (error) => {
  27. return Promise.reject(error)
  28. }
  29. )
  30. // Response Interceptor (에러 처리)
  31. apiClient.interceptors.response.use(
  32. (response) => {
  33. console.log('[useApi] Response:', response.config.url, response.status)
  34. return response
  35. },
  36. (error) => {
  37. const status = error.response?.status
  38. const url = error.config?.url
  39. console.log('[useApi] Error:', {
  40. url,
  41. status,
  42. message: error.message,
  43. hasToken: !!localStorage.getItem('admin_token')
  44. })
  45. // 401 에러만 토큰 삭제 및 로그아웃 처리
  46. if (status === 401) {
  47. console.log('[useApi] 401 Unauthorized - 토큰 삭제 및 로그아웃')
  48. if (typeof window !== 'undefined') {
  49. localStorage.removeItem('admin_token')
  50. localStorage.removeItem('admin_user')
  51. window.location.href = '/admin'
  52. }
  53. } else {
  54. console.log('[useApi] 401이 아닌 에러 - 토큰 유지')
  55. }
  56. return Promise.reject(error)
  57. }
  58. )
  59. export const useApi = () => {
  60. // GET 요청
  61. const get = async (url, params = {}) => {
  62. try {
  63. const response = await apiClient.get(url, { params })
  64. // CodeIgniter API 응답 구조: { success, data, message }
  65. return { data: response.data.data, error: null }
  66. } catch (error) {
  67. return { data: null, error: error.response?.data || error.message }
  68. }
  69. }
  70. // POST 요청
  71. const post = async (url, data = {}) => {
  72. try {
  73. const response = await apiClient.post(url, data)
  74. // CodeIgniter API 응답 구조: { success, data, message }
  75. return { data: response.data.data, error: null }
  76. } catch (error) {
  77. return { data: null, error: error.response?.data || error.message }
  78. }
  79. }
  80. // PUT 요청
  81. const put = async (url, data = {}) => {
  82. try {
  83. const response = await apiClient.put(url, data)
  84. // CodeIgniter API 응답 구조: { success, data, message }
  85. return { data: response.data.data, error: null }
  86. } catch (error) {
  87. return { data: null, error: error.response?.data || error.message }
  88. }
  89. }
  90. // DELETE 요청
  91. const del = async (url) => {
  92. try {
  93. const response = await apiClient.delete(url)
  94. // CodeIgniter API 응답 구조: { success, data, message }
  95. return { data: response.data.data, error: null }
  96. } catch (error) {
  97. return { data: null, error: error.response?.data || error.message }
  98. }
  99. }
  100. // 파일 업로드
  101. const upload = async (url, formData) => {
  102. try {
  103. const response = await apiClient.post(url, formData, {
  104. headers: {
  105. 'Content-Type': 'multipart/form-data'
  106. }
  107. })
  108. // CodeIgniter API 응답 구조: { success, data, message }
  109. return { data: response.data.data, error: null }
  110. } catch (error) {
  111. return { data: null, error: error.response?.data || error.message }
  112. }
  113. }
  114. return {
  115. get,
  116. post,
  117. put,
  118. del,
  119. upload
  120. }
  121. }