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

Fetch - 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

Fetch API JavaScript HTTP. fetch(), .

XMLHttpRequest. Fetch , , Service Workers. Fetch HTTP , CORS HTTP.

, fetch jQuery.ajax() :

  • Promise fetch() "" - HTTP, , HTTP 404 500. , ( false ok ) - .
  • , fetch cookie , , , ( cookie init options credentials omit).

. :

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  });

JSON . fetch() , , promise, ( Response).

, HTTP-, JSON. JSON , json() ( Body, Request Response.)

Fetch- connect-src (Content Security Policy), .

In this article

fetch() - init, :

js
//   POST :
async function postData(url = "", data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    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, *client
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return await response.json(); // parses JSON response into native JavaScript objects
}

postData("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON data parsed by `response.json()` call
});

fetch().

( cross-origin ), credentials: 'include' init, fetch():

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

URL (origin) , 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() POST- JSON.

js
const url = "https://example.com/profile";
const data = { username: "example" };

try {
  const response = await fetch(url, {
    method: "POST", //  'PUT'
    body: JSON.stringify(data), //    ''  {}!
    headers: {
      "Content-Type": "application/json",
    },
  });
  const json = await response.json();
  console.log(":", JSON.stringify(json));
} catch (error) {
  console.error(":", error);
}

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

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

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

try {
  const response = await fetch("https://example.com/profile/avatar", {
    method: "PUT",
    body: formData,
  });
  const result = await response.json();
  console.log(":", JSON.stringify(result));
} catch (error) {
  console.error(":", error);
}

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

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

formData.append("title", "   ");
for (let i = 0; i < photos.files.length; i++) {
  formData.append("photos", photos.files[i]);
}

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

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

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

  let 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);
  }
}

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

fetch() promise (reject) TypeError, CORS , , 404 . fetch() , promise (resolved), , Response.ok true. :

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

, fetch(), , Request(), fetch() :

js
const myHeaders = new Headers();

const myInit = {
  method: "GET",
  headers: myHeaders,
  mode: "cors",
  cache: "default",
};

const myRequest = new Request("flowers.jpg", myInit);
const response = await fetch(myRequest);
const myBlob = await response.blob();
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;

Request() , fetch(). :

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

, (..: "are one use only"). / , 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");

:

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")); // [ ]

ServiceWorkers, API .

Headers TypeError, HTTP Header. TypeError ( ) (..: "if there is an immutable guard"). . :

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

. :

js
try {
  const response = await fetch(myRequest);
  const contentType = response.headers.get("content-type");
  if (!contentType || !contentType.includes("application/json")) {
    throw new TypeError(",    JSON!");
  }
  const json = await response.json();
  /_   JSON _/;
} catch (error) {
  console.log(error);
}

, , , guard. Web, , .

:

none: .request: , (Request.headers).request-no-cors: , Request.mode no-cors.response: Headers (Response.headers).immutable: , ServiceWorkers; read-only.

: request Headers' Content-Length. , Set-Cookie : ServiceWorkers cookies .

, Response fetch() .

- :

Response.status ( 200) .Response.statusText ( "OK"), HTTP .Response.ok , - 200-299 . Boolean.

JavaScript, -, respondWith():

js
const myBody = new Blob();

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

Response() init ( , Request())

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

. :

ArrayBufferArrayBufferView (Uint8Array )Blob/FilestringURLSearchParamsFormData

Body ( Request Response). promise, .

arrayBuffer() blob() json() text() formData()

, XMR.

:

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

request response (and by extension the fetch() function), . request Content-Type , .

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

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


Web Proxy Viewer  |  New URL  |  Original Page