ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Toy Project 기록하기 2] axios로 HTTP 요청 보내기
    Frontend/Projects 2023. 2. 19. 21:55

     

    axios는 JavaScript를 사용하여 HTTP 요청을 보내는 비동기 통신 라이브러리입니다.

    axios를 사용하여 HTTP GET, POST, PUT, DELETE 등의 요청을 보내 백엔드로부터 필요한 데이터를 받아올 수 있습니다.

     

     


     

     

    axios의 사용법을 알아보고 프로젝트에서 axios를 어떻게 적용했는지 알아보겠습니다.

     

    axios 사용법

    axios 설치하기

    npm install axios

     

    GET

    상황

    주로 서버로부터 데이터를 가져올 때 사용합니다.

     

    사용법

    • 단순 데이터를 요청할 경우
    axios.get('/api/data')
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });

     

    • 파라미터 데이터를 포함시키는 경우
    axios.get('/api/data', {
          params: {
            id: 123
          }
        })
        .then(function (response) {
        	console.log(response.data);
        }).catch(function (error) {
        	console.log(error);
        });

     

    POST

    상황

    JSON 데이터를 서버로 보내기 위해 사용합니다.

     

    사용법

    const data = {
      title: 'hello',
      text: 'This is my feed.'
    };
    
    axios.post('/api/feed', data)
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });

     

    ✅ get과 post의 차이점

    get 메소드는 파라미터 데이터를 포함 시, 주소 뒤에 쿼리스트링으로 추가되어 정보를 전달합니다. 이 때 사용자의 비밀번호 등 민감한 정보가 노출될 수 있기 때문에 이러한 정보를 포함하고 있다면 post 메소드로 요청하는 것이 안전합니다. 

    일반적으로 get 메소드는 컨텐츠를 반환하는 용도로 사용하는 것이 좋고, post 메소드는 새로운 데이터를 서버로 보내는 용도로 사용하는 것이 좋습니다. 

     

    DELETE

    상황

    api 경로에 있는 사용자의 데이터를 삭제하기 위해 사용합니다.

     

    사용법

    axios.delete('/api/feed')
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });

     

    PUT

    상황

    api 경로에 있는 사용자의 데이터를 업데이트하기 위해 사용합니다.

     

    사용법

    const feed = {
      title: 'nice',
      text: 'Have a nice day!' 
    };
    
    axios.put('/api/feed', data)
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });

     

    내 프로젝트에 적용하기

    토이 프로젝트에서 Feed의 Create, Read, Update, Delete 과정에서 axios를 사용했습니다.

     

    먼저 axiosInstance를 따로 만들어 기본 설정을 적었습니다. 이제 axios가 필요한 곳에서 공통 셋팅이 완료된 axios를 끌어다 쓸 수 있습니다.

    // utils/axios.ts
    
    import axios, { AxiosResponse } from 'axios';
    
    // custom한 axiosInstance를 따로 만들기
    export const axiosInstance = axios.create({
      baseURL: 'http://localhost:4000',
      // cross-site access-control 요청을 허용 유무. true 시 cross-origin으로 쿠키 값 전달 가능.
      withCredentials: true,
    });

     

    그리고 feed의 CRUD에서 다음과 같이 axios 요청했습니다.

    // services/feed.ts
    
    export const getFeeds = ({ cursor, limit }: TCursorPagingVariables) => {
      // ✨ params를 포함하는 get 요청 
      return axiosInstance.get<TCursorPagingVariables, TCursorPaging<TFeed>>(
        '/feed',
        {
          params: { cursor, limit },
        }
      );
    };
    
    export const getFeed = ({ _id }: TGetFeedMutation) => {
      // ✨ 단순 feed data를 요청하는 get 요청 
      return axiosInstance.get<TFeed>(`/feed/${_id}`);
    };
    
    export const uploadFeed = async ({
      title,
      text,
      photoFile,
    }: TUploadFeedMutation) => {
      const formData = new FormData();
      formData.append('title', title);
      formData.append('text', text);
      photoFile && formData.append('photo', photoFile);
      // ✨ formData를 post 요청 
      return axiosInstance.post(`/feed`, formData);
    };
    
    export const updateFeed = async ({
      _id,
      title,
      text,
      photoFile,
    }: TUpdateFeedMutation) => {
      const formData = new FormData();
      formData.append('title', title);
      formData.append('text', text);
      photoFile && formData.append('photo', photoFile);
      // ✨ formData를 put 요청 
      return await axiosInstance.put(`/feed/${_id}`, formData);
    };
    
    export const deleteFeed = ({ _id }: TDeleteFeedMutation) => {
      // ✨ delete 요청 
      return axiosInstance.delete(`/feed`, {
        data: { _id },
      });
    };

     

    🧗‍♀️ 제가 진행한 프로젝트가 궁금하다면

    🔽 프론트엔드는 이곳에서 확인하실 수 있습니다.

    https://github.com/Team-Madstone/doljabee-fe

     

    GitHub - Team-Madstone/doljabee-fe: Climbing Community

    Climbing Community. Contribute to Team-Madstone/doljabee-fe development by creating an account on GitHub.

    github.com

     

    🔽 백엔드는 이곳에서 확인하실 수 있습니다.

    https://github.com/Team-Madstone/doljabee-be

     

    GitHub - Team-Madstone/doljabee-be: Climbing Community

    Climbing Community. Contribute to Team-Madstone/doljabee-be development by creating an account on GitHub.

    github.com

     

    참고 자료

    https://axios-http.com/kr/docs/intro

    반응형

    댓글

Designed by Tistory.