Axios GET Method에 데이터 추가하기

Franklee·2023년 2월 21일
0
post-thumbnail

My Study

GET은 HTTP method중 하나로 주로 서버에 데이터요청 통신시, 데이터를 조회(가져오기)시 사용하는 method이다.

Axios HTTP 별칭

  • axios.get(url[, config])
  • axios.post(url[, data[,config]])
  • axios.put(url[, data[,config]])

get은 다른 method와 비교시 data부분이 포함되어 있지 않다.
그러므로 axios.get(url,data) 형태로 method를 사용해도 서버측에서 req를 봐도 undefined를 출력하게 된다.


How to use

이를 해결하는 방법으로는 요청에 params를 사용하여 전송하는 방식을 사용하면 된다.

axios.get('https://somewhere.com',{ params : { data : something }});

Interceptor 사용시(+typeScript),

//파일
let initialData: sendAxiosState = {
      url: `http://somewhere.com`,
      data: {
        code: code, //params에 보낼 데이터...
      },
      callback: (response: AxiosResponse) => {
        //응답처리...
      },
    };
getInterceptor(initialData);

//interceptor 파일
export const getInterceptor = async (data: sendAxiosState) => {
  return instance
    .get(data.url, { params: data.data })
    .then((response: AxiosResponse) => {
      data.callback(response);
    })
    .catch((e) => {
      console.log(e);
    });
};

params를 통해 데이터를 요청에 포함하여 보내고, 서버측에서 해당 데이터를 사용하여 검색하고자 하는 특정 데이터를 찾는 방식을 사용한다.

profile
Frontend Dev

0개의 댓글