[CS] fetch, post, json

insung·2024년 6월 26일

CS

목록 보기
3/19

fetch

  • 첫번째 인자로 URL, 두번째 인자로 options
  • option에 아무것도 넣지 않으면 기본적으로 GET방식으로 호출
  • 처리 중 상태 (pending)
  • 실행결과는 promise 타입의 객체를 반환 (처리완료 상태)
    • 반환된 promise 객체는 API호출성공시 응답객체(response)를 반환 →fulfilled
      • 응답데이터를 받는 방법
        • reponse.text();
        • response.json();
        • response.formData();
        • reponse.blob();
    • 실패시엔 예외(error)객체를 반환함 → (reject)
  • 단일패치시엔 fetch then 활용하면 효율적
  • 그외에는 async await 사용하기
<script>
let response = await fetch(url);
if(response.ok)
{
let json = await response.json();
} else
{
alert("에러발생")
}
</script>

fetch('https://api.example.com/nonexistent')
  .then(response => {
    if (!response.ok) {
      throw new Error('HTTP error! Status: ' + response.status);
    }
    return response.json(); // JSON 데이터 추출
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Fetch error: ', error); // HTTP 요청 실패 또는 네트워크 오류 처리
  });
// GET 요청을 보낼 URL
const url = 'https://api.example.com/data';

// 헤더 설정을 포함한 fetch 요청
fetch(url, {
  method: 'GET', // 요청 메서드
  headers: {
    'Content-Type': 'application/json', // 원하는 헤더를 여기에 추가
    'Authorization': 'Bearer YourAccessToken', // 인증 토큰을 추가할 수도 있음
    // 다른 원하는 헤더도 추가 가능
  },
})
  .then(response => {
    if (!response.ok) {
      throw new Error('HTTP error! Status: ' + response.status);
    }
    return response.json(); // JSON 데이터 추출
  })
  .then(data => {
    console.log(data); // 성공한 경우 데이터 출력
  })
  .catch(error => {
    console.error('Fetch error: ', error); // 에러 처리
  });

post방식

  • method option : POST 설정
  • headers option : Contetn-Type JSON사용여부 결정
  • body option : 요청 data 값을 JSON형식으로 직렬화 하여 설정
  • PUT방식도 method option만 PUT으로 수정하면 나머지는 거의 비슷

json 직렬화와 역직렬화

  • 직렬화 (json 객체 → 문자로 변환)
    • JSON 형식의 문자열로 변환하는 과정을 의미합니다. 이 과정은 JSON.stringify() 함수를 사용하여 수행
  • 역직렬화 (문자열 → json객체로)
    • 문자열에서 데이터를 추출하여 JavaScript 객체나 데이터 구조로 변환하는 과정을 의미합니다. 이 과정은 JSON.parse() 함수를 사용하여 수행

직렬화(Serialization)는 데이터나 객체를 특정 형식(일반적으로 바이트 스트림 또는 문자열)으로 변환하는 과정을 의미 변환된 데이터는 저장, 전송 또는 공유될 수 있다, 나중에 역직렬화를 통해 원래 형식으로 복원될 수 있다.

목적 : 데이터 저장, 데이터 전송, 상태저장 및 복원, 데이터 교환

profile
안녕하세요 프론트엔드 관련 포스팅을 주로 하고 있습니다

0개의 댓글