리액트 - AJAX

코쓱타드·2023년 6월 6일
0
post-thumbnail

'AJAX가 뭔가요?'

서버에 GET, POST 요청을 할 때 새로고침 없이 데이터를 주고받을 수 있게 도와주는 간단한 브라우저 기능이다.

AJAX GET/POST 요청하는 방법중 가장 편한 방법은

‘axios’ 외부 라이브러리 사용하기!

1. GET : 데이터를 가져오려 할 때

> npm install axios (터미널에서 설치)
> 
// 메인파일에서 import
import axios from 'axios'

function App(){
  return (
    <button onClick={()=>{
      axios.get('https://codingapple1.github.io/shop/data2.json')
			.then((result)=>{ //then은 성공했을 때 실행할 코드
	        console.log(result.data);
      })
      .catch(()=>{ //catch는 실패했을 때 실행할 코드를 작성한다.
        console.log('실패함')
      })
    }}>GET 요청</button>
  )
}

GET 요청 숙제

Q. 하단의 버튼을 눌러 데이터를 받아와서 html로 나타내기.

<button
  onClick={() => {
	 axios
      .get("https://codingapple1.github.io/shop/data2.json")
       .then((result) => {
// [...shoes,...result.data] 는 shoes의 데이터와 get요청해서 가져온 데이터를 합치는 작업!
          let shoes3 = [...shoes, ...result.data];
          changeShoes(shoes3);
          })
        .catch(() => {
          console.log("실패함");
          });
        }}
       >
         GET요청하기
        </button>

1. POST : 데이터를 서버로 보내려 할 때

axios.post('url', {name : "koh"})

<동시에 ajax 요청 여러 개 하는 방법>

1.Promise.all( )

Promise.all([axios.get('첫번째 ajax요청 url'),axios.get('두번째 ajax요청 url')])
.then(()=>{//두개의 요청이 전부 성공하면 여기 코드가 실행된다})

2. fetch( )

브라우저 기본문법이라서 라이브러리 도움을 받지 않고도 ajax 요청 가능.



`출처. 코딩애플`
profile
개발자의 길 from 2022.12

0개의 댓글

관련 채용 정보