티스토리 뷰

일단 여기에 이어서 함.

 

1. axios 모듈을 받아야 함.

npm install axios

 

2. client.ts 파일 생성

touch src/scripts/client.ts

 

3. client.ts 파일 작성 

import axios, { InternalAxiosRequestConfig } from 'axios';

const client = axios.create({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Cache-Control': 'no-store',
  },
  withCredentials: true,
});

export const getData = async (
  url: string,
  params?: any,
  config?: InternalAxiosRequestConfig,
) => {
  try {
    const { data } = await client.get(url, { params, ...config });
    return data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      throw error.response;
    } else {
      console.log(error);
    }
  }
};

삽질하다가 'InternalAxiosRequestConfig'를 알게 되었음.

Axios 라이브러리 내부에서 사용되는 타입으로, Axios 요청의 구성을 정의하는 데 사용됨.

 

4. 사용할 곳에서 getData import 하여 사용

나는 store에서 사용했음.

import { defineStore } from 'pinia';

import { getData } from '@/scripts/conntectServer';

... 생략 ...

export const useFetchStore = defineStore({
  id: 'fetch',
  state: (): axiosInfo => ({ 
    data: '',
    ... 생략 ...
  }),
  actions: {
    ... 생략 ...
    async fetchGetContents(
      uri: string,
      data?: object,
    ) {
      try {
        const response = await getData(uri, { ...data });
        
        this.$patch({
          data: response,
        });	
        } catch (error) {
          console.log(error);
        }
      },
    },
});

 

 

참고 블로그 : 여기

반응형
LIST
댓글
링크
공지사항
최근에 올라온 글