Axios 사용법

hey hey·2022년 1월 11일
0

REACT 재정리

목록 보기
1/6
post-thumbnail

Axios 사용법

npm i axios

import axios from 'axios'

를 하고 사용하게 된다.

axios.get()

get 메서드를 사용하는 상황은 크게 두가지 존재한다.

  • 단순 데이터 요청을 수행할 경우
  • 파라미터 데이터를 포함시키는 경우 (사용자 번호에 따른 조회)

단순 데이터 요청

useEffect(()=>{
  axios.get("https://jsonplaceholder.typicode.com/users")
  .then(response=>{
    getUsers(response.data)
  })
})

async & await 사용법

const getData =(async()=>{
	try{
	  const response = await axios.get("https://jsonplaceholder.typicode.com/users")
	  getUsers(response.data)
	  }catch{
	  console.log('오류')
	  }
	})
useEffect(()=>{
  getData()
},[])

파라미터 데이터를 포함할 때

params 에 필요한 데이터를 함게 보내준다.

axios.get("url",{params:{id:123} })
.then(response=>{ ...})

axios.post()

포스트 메서드에는 일반적으로 데이터를 Message Body에 포함시켜 보낸다.

axios.post("url",{
		username:"hi",
		password:"123"
})
.then(...)

axios.put()

서버적으로 get→post 과정을 거치기 때문에 post 메서드와 비슷하다.

axios.put("url",{ ...}).then(...)

회원가입 만들어보기

import axios from 'axios'
axios.post("http://localhost:8080/signup",{
  userId:userId,
  password:password,
  username:username,
  email,email
}).then(response=>{
  if (response.data.code===0){
    setPopup({
      open:true,
      title:"Confirom",
      message:"Join Success",
      callback: function(){navigate("/login")}
    })
  } else{
    let message = response.data.message;
    if(response.data.code ===10000){
      message = "User ID is duplicated. "
    }
    setPopup({
      open: true,
      title: "Error",
      message: message
    })
  }
}).catch(error=>console.log(error))

  • code가 0 이외의 나머지는 에러팝업을 띄우게 하였다.
  • 중복 아이디로 회원가입 시도시 에러를 모달창에 띄우게 하였다.
  • callback 함수로 회원가입이 완료되고 모달창의 확인을 누르면 /login 페이지로 이동이 된다.

참고 https://gom20.tistory.com/m/171

profile
FE - devp

0개의 댓글