본문 바로가기

02. JavaScript/01. 기본개념, 문법 (ES6)

JavaScript_02. 문법_12_Fetch API

※ 본 내용은 해당 교재를 참고하여 공부한 내용과 본인의 생각을 정리한 글입니다.

https://www.yes24.com/Product/Goods/105608999

 

바닐라 자바스크립트 - 예스24

실무 역량까지 한 번에 잡을 수 있는바닐라 자바스크립트 이론서자바스크립트는 이제 브라우저를 넘어 웹 애플리케이션뿐만 아니라 마이크로 컨트롤러까지 점점 사용하는 곳이 늘어나고 있다.

www.yes24.com

 

 

 Fetch API는 네트워크 통신을 포함한 리소스 취득을 위한 인터페이스가 정의되어 있다

Fetch API XMLHttpRequest의 가장 큰 차이점은 Fetch API Promise방식으로 구현되어 있다는 점이다.

Promise에 대해서는 따로 설명. 

 

앞에서 했던 XMLHttpRequest와 유사한 개념들이라 딱히 설명할 게 없다. 예제 코드 보면서 사용법 익히기. 

 

<!DOCTYPE html>
<html>

<head>
  <title>Document</title>
</head>

<body>
  <script>
    //id가 1인 데이터 조회
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => console.log(json));

    /* 첫 번째 then() 함수는 '서버 요청에 대한 응답이 왔을 때' 실행된다. 
    이때 응답받은 데이터는 문자열 형식이기 때문에 
    repsonse.json() 함수를 호출해서 json 데이터로 변경을 실행
    json 데이터로 변경이 완료되면 두 번째 then() 함수의 매개변수로 변경된 json 데이터를 전달*/



    //POST - 데이터 생성
    fetch("https://jsonplaceholder.typicode.com/posts", {
      method: "POST", //HTTP 요청 방법
      body: JSON.stringify({
        //전송할 데이터
        title: "foo",
        body: "bar",
        userId: 1,
      }),
      headers: {
        //헤더 값 정의
        "content-type": "application/json; charset=UTF-8", //content-type 정의
      },
    })
      .then((response) => response.json())
      .then((json) => console.log(json));

    // HTTP 요청 방법은 method에, 전송할 데이터는 body에, 헤더 값은 headers에 정의하면 된다.



    //PUT - 데이터 수정
    fetch("https://jsonplaceholder.typicode.com/posts/1", {
      method: "PUT",
      body: JSON.stringify({
        id: 1,
        title: "foo",
        body: "bar",
        userId: 1,
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
    })
      .then((response) => response.json())
      .then((json) => console.log(json));

    //POST와 동일하며 method에서 post가 아닌 put을 사용한다.



    //DELETE - 데이터 삭제
    fetch("https://jsonplaceholder.typicode.com/posts/1", {
      method: "DELETE",
    });



    //파일 전송
    let formData = new FormData(); // FormData 객체 생성. FormData는 파일을 포함한 데이터를 전송할 수 있도록 해주는 객체.
    let fileField = document.querySelector('input[type="file"]'); //사용자가 선택한 파일

    formData.append("username", "abc123"); // 텍스트 데이터
    formData.append("attachment", fileField.files[0]); // 파일

    fetch("url", { method: "POST", body: formData })
      .then((response) => response.json())
      .catch((error) => console.error("Error:", error))
      .then((response) => console.log("Success: ", JSON.stringify(response)));

    //2개 이상의 다중 파일 전송
    let formData2 = new FormData();
    let fileField2 = document.querySelector('input[type="file"][multiple]');

    formData2.append("title", "My photos"); // 텍스트 데이터
    for (let i = 0; i < photos.files.length; i++) {
      formData2.append("photos", photos.files[i]); // 파일
    }

    fetch("url", { method: "POST", body: formData2 })
      .then((response) => response.json())
      .catch((error) => console.error("Error:", error))
      .then((response) => console.log("Success: ", JSON.stringify(response)));
  </script>
</body>

</html>

 

console