stella0905 2023. 5. 7. 19:08

Axios는 브라우저와 Node.js에서 사용할 수 있는 Promise 기반의 HTTP 클라이언트 라이브러리이다.

 

Axios를 사용하면 간단한 방법으로 HTTP 요청을 보낼 수 있습니다. GET, POST, PUT, DELETE 등 다양한 HTTP 요청 방식을 지원하며, JSON, URL 인코딩, 멀티파트 등의 다양한 형식의 데이터를 처리할 수 있다.

 

Axios는 또한 요청과 응답에 인터셉터(Interceptor)를 사용할 수 있습니다. 인터셉터는 요청이나 응답을 가로채서 처리할 수 있으며, 예를 들어 요청 시 인증 토큰을 설정하거나 응답 데이터를 처리하는 등의 작업을 수행할 수 있다.

 

Axios는 매우 간단하고 직관적인 API를 제공하기 때문에, 많은 개발자들이 자바스크립트나 리액트와 함께 사용한다.

 

 

예제

import axios from "axios";
import Cookies from "js-cookie";


const instance = axios.create({
  baseURL: process.env.REACT_APP_LOGIN_SERVER_URL
})

//회원가입 API
const handleSignUp = async (props) => {
  try {
    const response = await instance.post(`/register`, {
      id: props.id,
      password: props.password
    })
    return response.data
  }
  catch (error) {
    if (error.response.status !== 201) {
      return error.response.data
    }
    throw new Error('회원가입 실패 ')
  }
}

//로그인 API
const handleLogin = async (props) => {
  try {
    const response = await instance.post(`/login`, {
      id: props.id,
      password: props.password
    })
    return response.data
  }
  catch (error) {
    if (error.response.status !== 201) {
      return error.response.data
    }
  }
  // throw new Error(error.message)
}

//인가 API
const getLoginData = async () => {
  const accessToken = Cookies.get('token');
  const response = await instance.get(`/user`, {
    headers: {
      "Content-Type": "application/json",
      authorization: `Bearer ${accessToken}`,
    }
  })

  return response
}
export { handleSignUp, handleLogin, getLoginData }