프로그래밍 언어와 기술/JavaScript

[JavaScript] fetch

tero1115 2023. 7. 24. 10:01

간단한 fetch 사용예시

fetch('https://api.example.com/data')
  .then(response => response.json()) // 응답 데이터를 JSON 형태로 파싱
  .then(data => {
    console.log(data); // 서버에서 받아온 데이터를 활용
  })
  .catch(error => {
    console.error('Error:', error); // 에러 처리
  });
fetch("/api/v1/post", {
    method : "POST",
    headers : {
        "Content-Type" : "application/json;charset=utf-8",
    },
    body : JSON.stringify(dto),
})
.then((response) => response.json())
.then((result) => {
    alert(result.message);
    if (result.code == 0) {
        location.replace("/");
    }
})