심플코더
간단한 코딩 공간
   

글쓰기    관리    수식입력
  • 분류 전체보기 (84)
    • AWS (1)
    • JavaScript (11)
    • 개인학습 (5)
    • DB (11)
    • OS (9)
    • Network (7)
    • DevOps (0)
    • TypeScript (1)
    • 개발 (1)
    • CKA (28)
hELLO · Designed By 정상우.
심플코더

간단한 코딩 공간

JavaScript

(JavaScript) Fetch API

Fetch API

Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공한다.

 

Fetch API가 제공하는 fetch() 함수를 활용하여 네트워크 리소스를 쉽게 비동기적으로 취득할 수 있다.

 

기본적인 리소스 취득 요청은 다음과 같다.

async function logJSONData() {
  const response = await fetch("http://example.com/movies.json");
  const jsonData = await response.json();
  console.log(jsonData);
}

위 소스는 입력된 네트워크를 통해 JSON 파일을 취득하여 콘솔에 출력한다. 

 

가장 단순하게 호출한 fetch()는 가져오고자 하는 리소스의 경로를 나타내는 하나의 파라미터만을 입력받는다.

 

응답은 Response 객체로 표현되며, json()을 통해 응답 객체를 JSON으로 파싱한 결과를 받고 있다.

 

fetch 함수에 두 번째 매개변수를 제공하여 다음과 같이 사용할 수 있다.

async function postData(url = "", data = {}) {
  // 옵션 기본 값은 *로 강조
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE 등
    mode: "cors", // no-cors, *cors, same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
      "Content-Type": "application/json",
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: "follow", // manual, *follow, error
    referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
  });
  return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}

postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});

url로 request 옵션을 제공할 수 있다. method, mode, cache등의 인자를 넣어 HTML 요청을 전송하고, 리턴으로 response를 받을 수 있다.

 

위 구조를 활용하여, POST 명령을 전송하면 다음과 같이 파일을 업로드 할 수 있다.

async function upload(formData) {
  try {
    const response = await fetch("https://example.com/profile/avatar", {
      method: "PUT",
      body: formData,
    });
    const result = await response.json();
    console.log("성공:", result);
  } catch (error) {
    console.error("실패:", error);
  }
}

const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');

formData.append("username", "abc123");
formData.append("avatar", fileField.files[0]);

upload(formData);

 

 

'JavaScript' 카테고리의 다른 글

(Node.js) Express에서 cookie, session 사용 방법  (1) 2023.09.11
ES class와 prototype  (0) 2023.09.11
MySQL 개념  (1) 2023.09.04
Express란?  (0) 2023.09.01
Firebase 사용 방법  (0) 2023.08.12
    'JavaScript' 카테고리의 다른 글
    • (Node.js) Express에서 cookie, session 사용 방법
    • ES class와 prototype
    • MySQL 개념
    • Express란?
    심플코더
    심플코더

    티스토리툴바