[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch [Back]  [Original]

Fetch API - Web API | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Fetch API

Fetch API HTTP JavaScript . Fetch API fetch() .

API XMLHttpRequest , Fetch API . Fetch API CORS HTTP .

.

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

JSON . fetch() . Response , JSON .

Response JSON . Response HTTP , JSON json() . json() JSON , .

: .

, Content-Security-Policy connect-src .

In this article

fetch() . , init .

fetch() , .

js
// POST   
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()`   
});

mode: "no-cors" .

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type, application/x-www-form-urlencoded, multipart/form-data, text/plain

fetch() AbortController AbortSignal .

js
const controller = new AbortController();
const signal = controller.signal;
const url = "video.mp4";

const downloadBtn = document.querySelector("#download");
const abortBtn = document.querySelector("#abort");

downloadBtn.addEventListener("click", async () => {
  try {
    const response = await fetch(url, { signal });
    console.log(" ", response);
  } catch (error) {
    console.error(` : ${error.message}`);
  }
});

abortBtn.addEventListener("click", () => {
  controller.abort();
  console.log(" ");
});

fetch() init credential: 'include' . .

js
fetch("https://example.com", {
  credentials: "include",
});

: credentials: 'include' , Access-Control-Allow-Origin . . CORS .

: , . CORS .

URL credentials: 'same-origin' .

js
//   'https://example.com'

fetch("https://example.com", {
  credentials: "same-origin",
});

credentials: 'omit' .

js
fetch("https://example.com", {
  credentials: "omit",
});

JSON

fetch() JSON POST .

js
async function postJSON(data) {
  try {
    const response = await fetch("https://example.com/profile", {
      method: "POST", //  'PUT'
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

    const result = await response.json();
    console.log(":", result);
  } catch (error) {
    console.error(":", error);
  }
}

const data = { username: "example" };
postJSON(data);

fetch() <input type="file"> , FormData() .

js
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);

fetch() <input type="file" multiple> , FormData() .

js
async function uploadMultiple(formData) {
  try {
    const response = await fetch("https://example.com/posts", {
      method: "POST",
      body: formData,
    });
    const result = await response.json();
    console.log(":", result);
  } catch (error) {
    console.error(":", error);
  }
}

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

formData.append("title", "My Vegas Vacation");

for (const [i, photo] of Array.from(photos.files).entries()) {
  formData.append(`photos_${i}`, photo);
}

uploadMultiple(formData);

, Uint8Array. , '' . . ( UTF-8 , .)

js
async function* makeTextFileLineIterator(fileURL) {
  const utf8Decoder = new TextDecoder("utf-8");
  const response = await fetch(fileURL);
  const reader = response.body.getReader();
  let { value: chunk, done: readerDone } = await reader.read();
  chunk = chunk ? utf8Decoder.decode(chunk) : "";

  const re = /\n|\r|\r\n/gm;
  let startIndex = 0;
  let result;

  for (;;) {
    let result = re.exec(chunk);
    if (!result) {
      if (readerDone) {
        break;
      }
      let remainder = chunk.substr(startIndex);
      ({ value: chunk, done: readerDone } = await reader.read());
      chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
      startIndex = re.lastIndex = 0;
      continue;
    }
    yield chunk.substring(startIndex, result.index);
    startIndex = re.lastIndex;
  }
  if (startIndex < chunk.length) {
    //       
    yield chunk.substr(startIndex);
  }
}

async function run() {
  for await (let line of makeTextFileLineIterator(urlOfFile)) {
    processLine(line);
  }
}

run();

fetch() , CORS TypeError . , 404 . fetch() , Response.ok true .

js
async function fetchImage() {
  try {
    const response = await fetch("flowers.jpg");
    if (!response.ok) {
      throw new Error("  OK ");
    }
    const myBlob = await response.blob();
    myImage.src = URL.createObjectURL(myBlob);
  } catch (error) {
    console.error("  :", error);
  }
}

fetch() , Request() .

js
async function fetchImage(request) {
  try {
    const response = await fetch(request);
    if (!response.ok) {
      throw new Error("  OK ");
    }
    const myBlob = await response.blob();
    myImage.src = URL.createObjectURL(myBlob);
  } catch (error) {
    console.error(":", error);
  }
}

const myHeaders = new Headers();

const myRequest = new Request("flowers.jpg", {
  method: "GET",
  headers: myHeaders,
  mode: "cors",
  cache: "default",
});

fetchImage(myRequest);

Request() fetch() . .

js
const anotherRequest = new Request(myRequest, myInit);

. , / init . .

: clone() . , . .

Headers Headers() . .

js
const content = "Hello World";
const myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

2 .

js
const myHeaders = new Headers({
  "Content-Type": "text/plain",
  "Content-Length": content.length.toString(),
  "X-Custom-Header": "ProcessThisImmediately",
});

.

js
console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue");

console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.get("X-Custom-Header")); // ['ProcessThisImmediately', 'AnotherValue']

myHeaders.delete("X-Custom-Header");
console.log(myHeaders.get("X-Custom-Header")); // null

, API .

Headers HTTP TypeError . ( ) TypeError . . .

js
const myResponse = Response.error();
try {
  myResponse.headers.set("Origin", "http://mybank.com");
} catch (e) {
  console.log("    !");
}

. .

js
async function fetchJSON(request) {
  try {
    const response = await fetch(request);
    const contentType = response.headers.get("content-type");
    if (!contentType || !contentType.includes("application/json")) {
      throw new TypeError(", JSON !");
    }
    const jsonData = await response.json();
    //   
  } catch (error) {
    console.error(":", error);
  }
}

, ''(guard) . , .

.

: Content-Length . ,Set-Cookie . , .

Response fetch() .

.

JavaScript , respondWith() .

js
const myBody = new Blob();

addEventListener("fetch", function (event) {
  // fetch  ServiceWorker
  event.respondWith(
    new Response(myBody, {
      headers: { "Content-Type": "text/plain" },
    }),
  );
});

Response() . , Request() .

: error() . , redirect() URL . .

. .

Request Response . , .

XHR .

body .

js
const form = new FormData(document.getElementById("login-form"));
fetch("/login", {
  method: "POST",
  body: form,
});

, fetch() . , Content-Type .

Fetch API Window Worker Headers, Request, Response, fetch() .

js
if (window.fetch) {
  // fetch  
} else {
  // XMLHttpRequest ?
}


Web Proxy Viewer  |  New URL  |  Original Page