React Axis

devyunie·2024년 9월 4일

React

목록 보기
20/20
post-thumbnail

axios 패키지

  • js에서 사용하는 HTTP 클라이언트 라이브러리
  • nodeJs와 브라우저 환경에서 동작함
  • Fetch API, jQuery기반의 Ajax 보다 간편함
  • axios는 기본적으로 비동기 처리를 수행

React axios package install

$ npm install axios

axios 객체

  • http method에 해당하는 메서드를 포함하고 잇음
  • 각각의 http method 메서드는 매개변수로 url, data, option 받을수 있음 ->data 주의 Request body 의미

http method 매개변수 종류

http method매개변수
get , deleteurl , option
post , put, patchurl , data , option

-> data는 Request Body를 의미한다.


http method GET

Current
  1. 각각의 http method메서드는 then으로 response 객체를 받는 콜백함수를 전달
  2. response 객체는 status, header, body(data)를 포함 하고 있음
Error
  1. http 요청에 대한 실패 (network error 400~500상태) 처리
  2. AxiosError 객체를 받아옴 만약 응답이 존재하는 실패일 경우 axioserror 객체 안이 response 속성으로 해당 응답에 접근
option 매개변수
  1. request에 대한 각종 설정
    axios
        .get('url 주소')
        // 올바른 전달
        .then((response)=>{
            console.log(response.data);
        })
      	//Error 전달
        .catch((error)=>{

            console.log(error)
        })

        axios.get('url 주소',{
            headers: {Authorization: 'Bearer token값'},
            params: { 'time': '1213'}
        })

http method Post

  • request body가 존재하는 요청에 대해서는 매개변수의 위치 주의
 axios
   .post('url 주소',{} ,{
	headers: {Authorization: 'Bearer token명'}
    params: { 'time': '1213'}
    })

CORS Error (Cross Origin Resource Sharing)

  • JS를 이용한 request 요청시 출처로 다른 요청에 대하여 자원 공유 정책

전체 소스코드

export default function Axios() {


    axios
        .get('url 주소')
        .then((response)=>{
            console.log(response.data);
        })
        .catch((error)=>{
            console.log(error)
        })

        axios.get('url 주소',{
            headers: {Authorization: 'Bearer otsdflsf'},
            params: { 'time': '1213'}
        })
        axios.post('url 주소',{} ,{
            headers: {Authorization: 'Bearer otsdflsf'},
            params: { 'time': '1213'}
        })

        //현재 CORS 정책이 차단 되어있어 naver로 이동이 불가능 하다.
        axios.get('https://naver.com')

    return (
        <div>Axios</div>
    )
}

0개의 댓글