[React] React Axios
[React] React Axios
Ajax란?
서버에 GET, POST 요청을 할 때 새로고침 없이 비동기적으로 데이터를 주고받을 수 있게 도와주는 간단한 브라우저 기능이다.
방법 3가지
Ajax로 GET/POST를 요청하는 방법은 3가지가 있다.
- XMLHttpRequest 라는 옜날 문법 쓰기
- fetch() 라는 최신 문법 쓰기
- axios 같은 외부 라이브러리 쓰기 (추천)
Axios를 설치해보자
https://axios-http.com/kr/docs/intro
터미널 열어서 npm 명령어를 입력한다.
1
npm install axios
Ajax GET 요청하는 법
- axios를 상단에 import 하고
- axios.get(url) 로 요청을 한다.
- 가져온 데이터를 사용한다. ````javascript import axios from ‘axios’
function App(){ return ( <button onClick={()=>{ axios.get(‘https://codingapple1.github.io/shop/data2.json’) .then((결과)=>{ console.log(결과.data) }) .catch(()=>{ console.log(‘실패함’) }) }}>버튼</button> ) }
1
2
3
4
5
6
7
8
9
10
11
12
## POST 요청하는 법
````javascript
axios.post('URL', {name : 'kim'})
.then((결과)=>{
console.log(결과.data)
})
.catch(()=>{
console.log('실패함')
})
동시에 여러개 요청하는 법
1
2
3
4
5
6
7
Promise.all( [axios.get('URL1'), axios.get('URL2')] )
.then((결과)=>{
console.log(결과.data)
})
.catch(()=>{
console.log('실패함')
})
fetch 최신문법 쓰기
이건 JSON -> object/array 로 자동변환을 안해줘서 직접 바꿔야 한다.
1
2
3
fetch('URL')
.then(결과 => 결과.json())
.then((결과) => { console.log(결과) } )
This post is licensed under CC BY 4.0 by the author.