Skip to content
On this page

http

서버와의 http 톻신은 axios library를 사용한다.
개별 프로그램에서는 axios를 import 하지 말고 http를 활용한다.

  • baseURL

    • /src/.env 파일의 VITE_AXIOS_BASEURL에 설정되 있음.
    • .env는 로컬서버, .env.dev는 개발서버, .env.prod는 운영서버의 url이 적용된다.
    • 메소드 호출시 url이 '/'로 시작하면 baseURL로 요청하고, 아니라면 그대로 호출한다.
  • Promise

    • http의 메소드는 Promise 패턴으로 사용한다.
    • http를 사용하는 함수에는 async를 붙이고, 함수 호출시 await를 붙인다.
        async function query() {
          const result = await http.post('/url', data)
          // result 처리
        }
      
    • async/await를 사용하기 어려운경우에는 then 패턴을 사용할 수 있다.
        function query() {
          http.post('/url', data)
          .then(function(result) {
            // result 처리
          })
        }
      
    • async/await의 즉시실행
        // App 시작시 로그인여부 검사를 즉시실행
        ; (async () => {
          await loginCheck()
          isLoadComplete.value = true
        })()
      
  • AxiosResponse

    • type
    export interface AxiosResponse<T = any>  {
      data: T;
      status: number;
      statusText: string;
      headers: any;
      config: AxiosRequestConfig;
      request?: any;
    }
    
    • 서버의 controller에서는 ResMap으로 return 한다.
    • ResMap의 생성자에 담는 값이 response의 data키에 저장되고, 함께 조회할 값은 put 메소드로 담는다.
    • 서버의 응답 결과는 AxiosResponsedata에 담기는데, 서버의 ResMap의 형태인 {data: any} 이다.
      AxiosResponse {
        data : {
          data: [],
          other: []
        }
      }
    
    • 대부분의 경우 AxiosResponse에서 data를 return 하는 post함수를 사용하고, header등의 다른 필드가 필요하면 AxiosResponse 자체를 return 하는 response를 사용한다.
    • 모든 조회, 저장은 post함수를 사용하고, 필요할 때만 get을 사용한다.

get & post

getGET 방식 호출에 사용하고 postPOST 방식 호출에 사용한다.
getpost는 이름만 다르고 사용법은 동일하다.
응답 결과는 서버에서는 return 하는 ResMap의 형태이다.

  • Type

      get<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<{
        data: T;
        [key: string]: any    
      }>;
    
      post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<{
        data: T;
        [key: string]: any    
      }>;
    
  • Expample

    • 조회결과의 키가 data 하나일때.

      @PostMapping("/query")
      public ResMap query(@RequestBody FormGridParam param) {
        return new ResMap(service.query(param))
      }
      
      const condData = reactive({
        param: 'value'
      })
      
      async function query() {
        const { data } = await http.post('/url/query', condData)
        flex.setData(data)
      }
      

      그리드 단독조회일 경우 그리드의 query 함수는 http.postflex.setData를 한번에 실행해준다.

      const condData = reactive({})
      async function query() {
        flex.query('/url/query', condData)
      }
      
    • 한번 조회(저장)으로 결과가 여러개의 키를 가질때

        @PostMapping("/query")
        public ResMap query(@RequestBody FormGridParam param) {
          /**
          * 조회결과가 여러개이면 ResMap을 chaing으로 여러번 put으로 담는다.
          */
          return new ResMap(service.query(param))
            .put("fileList", service.queryUpload(param))
            .put("other", "다른 데이터");
        }
      
      const condData = reactive({
        param: 'value'
      })
      const other = ref()
      async function query() {
        // 1. result 변수로 받음
        const result = await http.post('/url/query', condData)
        flex.setData(result.data) // 그리드 데이터
        flexFile.setData(result.fileList) // 그리드 첨부파일 데이터
        other.value = result.other // 그리드 아닌 데이터
      
        // 2. 구조분해 방식 
        const { data, fileList, other } = await http.post('/url/query', condData)
        flex.setData(data)
        flexFile.setData(fileList) // 그리드 첨부파일 데이터
        other.value = other
      }
      

upload

첨부파일이 있는 저장일때는 post가 아닌 upload 함수를 사용한다. saveData는 저장할 json 데이터 이고, uploadSaveData에는 첨부파일 정보 이다.

  • Type
    upload(
      url: string,
      saveData: any,
      uploadSaveData?: UploadSaveData,
      config?: AxiosRequestConfig)
      : Promise<{
        data: any;
        [key: string]: any    
      }>;
    
    interface UploadSaveData {
      addFileData: CmmFile[]
      removeFileData: CmmFile[]
      files: File[]
    }
    

response

getpostAxiosResponsedata값을 return 하는데, responseheaders 등 별도의 처리가 필요할 경우 AxiosResponse를 return 하는 response 함수를 사용한다.

response(url: string, data?: any, config?: AxiosRequestConfig): AxiosResponse
async function loginCheck(): Promise<void> {
  try {
    const response = await http.response<User>('/user/getLoginData')
    if (response.headers.authorization) {
      user.value = response.data
      storage.set(AuthKey.JWT, response.headers.authorization, true)
      return Promise.resolve()
    }
  } catch (e) {
    throw '로그인 검사 예외'
  }
}

Hello