[React] Ajax

Hoeon·2024년 5월 25일
1

React

목록 보기
5/6
post-thumbnail

0. 배경

서버 : 요청 시 그에 따른 응답을 해주는 프로그램.

  • 어떤 방법(GET/POST)으로 어떤 데이터(URL)를 원하는 지 요청

1. Ajax

❓ 브라우저 주소창에 get/post 요청시 새로고침이 일어남.
Ajax(Asynchronous JavaScript And XML)는 자바스크립트를 사용해 비동기적으로 데이터를 받아와 동적으로 DOM을 갱신하고 조작하는 기법.
-> 비동기적으로 동작하기 때문에 서버와 통신 후 페이지 새로고침이 일어나지 않는다.

종류: XMLHttpRequeust API / fetch / axios

1.1. axios

  • js 라이브러리 (npm install axios)
import axios from 'axios'

function App(){
  return (
    <button onClick={()=>{
      axios.get('https://codingapple1.github.io/shop/data2.json')
        .then((response)=>{
        	console.log(response.data)
      })
      	.catch(()=>{
        	console.log('실패함')
      })
    }}>버튼</button>
  )
}
import axios from 'axios'

function App(){

  let [shoes, setShoes] = useState(어쩌구);
  return (
    <button onClick={()=>{
      axios.get('https://codingapple1.github.io/shop/data2.json').then((response)=>{
        let copy = [...shoes, ...response.data]
        setShoes(copy)
      })
      .catch(()=>{
        console.log('실패함')
      })
    }}>버튼</button>
  )
}

1.2. POST

axios.post('URL', {name : 'kim'})
	.then(()=>{})

1.3. 동시에 ajax 요청 날리기

Promise.all( [axios.get('URL1'), axios.get('URL2')] )
	.then(()=>{})

2. fetch 보다 axios를 쓰는 이유?

axios.get('/api/users')
  .then(response => {
    // 응답 데이터 처리
    console.log(response.data);
  })
  .catch(error => {
    // 에러 처리
    console.error(error);
  });


fetch('/api/users')
  .then(response => response.json())
  .then(data => {
    // 응답 데이터 처리
    console.log(data);
  })
  .catch(error => {
    // 에러 처리
    console.error(error);
  });

axios 같은 경우 응답 데이터를 response.data 형식으로 손쉽게 처리하지만, fetch 방식은 .json() 메서드를 사용하여 응답 데이터를 JSON 형식으로 파싱해야한다.

axios.post('/api/users', { name: 'John', age: 25 })
  .then(response => {
    // 응답 데이터 처리
    console.log(response.data);
  })
  .catch(error => {
    // 에러 처리
    console.error(error);
  });


fetch('/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John', age: 25 })
})
  .then(response => response.json())
  .then(data => {
    // 응답 데이터 처리
    console.log(data);
  })
  .catch(error => {
    // 에러 처리
    console.error(error);
  });

axios에서 데이터는 두 번째 인자로 전달되고, 응답 데이터는 response.data로 접근 가능, fetch에서는 post 요청을 위해 요청 설정 객체에 method, headers, body 등을 명시해야 함. 또한 응답 데이터도 JSON 형식으로 파싱 필요.

profile
프론트엔드 개발자 준비생 •~•

0개의 댓글