Fetch/Axois 차이점

toddcanwell·2025년 8월 23일

요청/응답

Fetch 는 웹브라우저에서 사용할수있는 내장함수 , HTTP 통신으로 서버로부터 데이터를 가져온다.

Axios 는 Fetch함수와 같이 HTTP 통신을 위한 자바스크립트 라이브러리로 , 여러 편리한 기능을 제공한다.

  • 요청 (request)

url : 요청 서버 주소

method : 요청 종류 ( GET 조회 , POST 생성 , PUT/PATCH 전체/일부 수정 , DELETE 삭제 )

headers : 요청하는 메타 정보

body : 요청하는 데이터

  • 응답 (response)

status : 응답 상태 (1xx 처리 중 , 2xx 성공, 3xx 리다이렉션 ,4xx 클라이언트오류 , 5xx 서버오류 … 200 정상적 , 400 잘못된 요청 , 401 인증정보 부족 , 403 권한없음 , 404 찾을수없음 , 500 서버오류 )

headers : 응답 메타 정보

body : 응답 데이터

ok : 정상 처리 여부


REQUEST 요청

  • Method
    // 모든 사용자 조회
    fetch('http://127.0.0.1:5000/hello', {
      method: 'GET' // 혹은 생략 가능!
    })
    // 혹은
    fetch('http://127.0.0.1:5000/hello')
    
    // 새로운 사용자 생성
    fetch('http://127.0.0.1:5000/hello', {
      method: 'POST',
      body: JSON.stringify({
        name: 'HEROPY',
        age: 85,
        emails: ['thesecon@gmail.com']
      })
    })
    
    // 사용자 정보 수정
    fetch('http://127.0.0.1:5000/hello/p1', {
      method: 'PUT',
      body: JSON.stringify({
        name: "HEROPY",
        emails: ['thesecon@gmail.com']
      })
    })
    
    // 사용자 삭제
    fetch('http://127.0.0.1:5000/hello/p1', {
        method: 'DELETE'
      })
  • Headers / Body
    Headers에는 메타정보 , body에는 실제 데이터가 들어간다.

  • Http Content-type
    요청/응답 body의 전송할 데이터 타입을 의미한다.
    서버·클라이언트는 이 값을 보고 어떻게 파싱(해석)할지 결정한다.
    ex)
    application/json : JSON 형식
    application/x-www-form-urlencoded : body부분의 key=value 형식 과 URL 인코딩을 진행하기에 대용량 파일
    에 쓰기에 적합하지않다.

   
   fetch('http://127.0.0.1:5000/hello', {
   	method: 'POST',
     headers: {
       'Content-type': 'application/json',
       Apikey: 'KDnREmPe9B1',
       Username: 'ParkYoungWoong',
       Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjlQS3I...',
       'X-Username': 'ParkYoungWoong',
       '...'
     },
      // 생성할 사용자 정보(데이터)
     body: JSON.stringify({
       name: 'HEROPY',
       age: 85
     })
   })

Fetch vs Axios

Fetch : Fetch 는 웹브라우저에서 사용할수있는 내장함수 , HTTP 통신으로 서버로부터 데이터를 가져온다.

body 옵션에 데이터를 담는다.

보낼 데이터를 JSON.stringfy 활용해 문자로 변환해 포함한다.

**fetch로 받아온 데이터를 json 메소드를 이용해 파싱해줘야 합니다.

Axios : Fetch함수와 같이 HTTP 통신을 위한 자바스크립트 라이브러리로 , 여러 편리한 기능을 제공한다.

data 옵션에 데이터를 담는다.

자동으로 JSON 문자로 변환된다.

response 된 데이터도 자동파싱된다.

fetch는 별도의 설치 없이 바로 사용할 수 있으며, axios는 보다 풍부한 기능과 간결한 API를 제공합니다.

fetch('http://127.0.0.1:5000/hello')
  .then(res => res.json())
  .then(data => console.log(data)) // { total: 7, users: User[] }
npm  i axios 

import axios from 'axios'

axios.get('http://127.0.0.1:5000/hello')
			.then(res => console.log(res.data)) // { total: 7, users: User[] }
  • 데이터 조회

    주로 GET 메소드 사용 , 생략이 가능하다.
    // fetch 사용시
    
    ;(async () => {
      // const res = await fetch('http://127.0.0.1:5000/hello', { method: 'GET' })
      const res = await fetch('http://127.0.0.1:5000/hello')
      const data = await res.json()
      console.log(data)
    })()
    
    // axios 
    
    import axios from 'axios'
    
    ;(async () => {
      // const res = await axios({ url: 'http://127.0.0.1:5000/hello', method: 'GET' })
      // const res = await axios.get('http://127.0.0.1:5000/hello')
      const res = await axios('http://127.0.0.1:5000/hello')
      console.log(res.data)
    })()
  • 데이터 생성

    body 옵션에 데이터를 담는다.
    보낼 데이터를 JSON.stringfy 활용해 문자로 변환해 포함한다.
    ;(async () => {
      const res = await fetch('http://127.0.0.1:5000/hello', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: 'HEROPY',
          age: 85,
          isValid: true,
          emails: ['thesecon@gmail.com']
        })
      })
      const data = await res.json()
      console.log(data)
    })()
    
    // axios
    
    ;(async () => {
      const res = await axios({
        url: 'http://127.0.0.1:5000/hello',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        data: {
          name: 'HEROPY',
          age: 85,
          isValid: true,
          emails: ['thesecon@gmail.com']
        }
      })
      console.log(res.data)
    })()
  • 데이터 삭제 ,수정

    데이터 전체수정시 PUT , PATCH (일부) DELETE 메소드 사용한다.
  ;(async () => {
  const res = await fetch('http://127.0.0.1:5000/hello/ywTTX', {
    method: 'DELETE'
  })
  const data = await res.json()
  console.log(data)
})()

;(async () => {
  const res = await axios({
    url: 'http://127.0.0.1:5000/hello/ywTTX',
    method: 'DELETE'
  })
  console.log(res.data)
})()
  
profile
toddcanwell

0개의 댓글