2024.06.14 Today Yoonsung Learned

Ryany (윤성)·2024년 6월 16일
post-thumbnail

TIL

Axios 사용법

  • axios 패키지 다운
yarn add axios
  • Import axios
import axios from "axios";
  • AUTH_API_HOST 상수를 정의하여 API 호스트 URL을 저장
const AUTH_API_HOST = "https://moneyfulpublicpolicy.co.kr";
  • 회원가입 함수 정의
export const register = async ({ id, password, nickname }) => {
  try {
    // axios를 사용하여 POST 요청을 보냄
   // 요청 URL은 AUTH_API_HOST + "/register"
   // 요청 데이터로 id, password, nickname을 전송
    const response = await axios.post(AUTH_API_HOST + "/register", {
      id: id,
      password: password,
      nickname: nickname,
    });
    // 응답 데이터를 반환
    return response.data;
  } catch (error) {
    // 에러 발생 시 에러 메시지를 콘솔에 출력
    console.log(error?.response?.data?.message);
    // 에러 메시지를 알림창으로 표시
    alert(error?.response?.data?.message);
  }
};
  • 로그인 함수 정의
export const login = async ({ id, password }) => {
  try {
    // axios를 사용하여 POST 요청을 보냄
   // 요청 URL은 AUTH_API_HOST + "/login?expiresIn=10m"
   // 요청 데이터로 id와 password를 전송
    const response = await axios.post(AUTH_API_HOST + "/login?expiresIn=10m",{
      id: id,
      password: password,
    });
    // 로컬 스토리지에 accessToken을 저장
    localStorage.setItem("accessToken, response.data.accessToken");
    // 응답 데이터를 반환
    return response.data;
  } catch (error) {
    // 에러 발생 시 에러 메시지를 콘솔에 출력
    console.log(error?.response?.data?.message);
    // 에러 메시지를 알림창으로 표시
    alert(error?.response?.data?.message);
  }
};
profile
Junior Developer :>

0개의 댓글