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

Fetch - Web API | MDN

MDN Web Docs

View in English Always switch to English

Fetch

Fetch API JavaScript HTTP fetch()

XMLHttpRequest Fetch Service WorkersFetch HTTP CORS HTTP

fetch jQuery.ajax()

  • HTTP fetch() Promise reject HTTP 404 500 Promise resolve HTTP 200 - 299 resolve ok false reject
  • fetch cookie credentials 2018 8 credentials same-originFirefox 61.0b13

fetch

js
fetch("http://example.com/movies.json")
  .then((response) => response.json())
  .then((data) => console.log(data));

JSON fetch() promise Response

HTTP JSON JSON json() body JSON promise

(CSP) fetch

fetch() init

fetch()

js
// Example POST method implementation:
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, *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 data type must match "Content-Type" header
  });
  return 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 `data.json()` call
});

mode: "no-cors" HTTP

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type application/x-www-form-urlencodedmultipart/form-data text/plain

credentials: 'include' fetch() init

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

credentials: 'include' Access-Control-Allow-Origin "*"Access-Control-Allow-Origin CORS Unblock

URL credentials: 'same-origin'

js
// The calling script is on the origin '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 data = { username: "example" };

fetch("https://example.com/profile", {
  method: "POST", // or 'PUT'
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
})
  .then((response) => response.json())
  .then((data) => {
    console.log("Success:", data);
  })
  .catch((error) => {
    console.error("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]);

fetch("https://example.com/profile/avatar", {
  method: "PUT",
  body: formData,
})
  .then((response) => response.json())
  .then((result) => {
    console.log("Success:", result);
  })
  .catch((error) => {
    console.error("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", "My Vegas Vacation");
for (let i = 0; i < photos.files.length; i++) {
  formData.append(`photos_${i}`, photos.files[i]);
}

fetch("https://example.com/posts", {
  method: "POST",
  body: formData,
})
  .then((response) => response.json())
  .then((result) => {
    console.log("Success:", result);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

Uint8Array fetch() UTF-8 fetch()

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) {
    // last line didn't end in a newline char
    yield chunk.substr(startIndex);
  }
}

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

run();

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

js
fetch("flowers.jpg")
  .then((response) => {
    if (!response.ok) {
      throw new Error("Network response was not OK");
    }
    return response.blob();
  })
  .then((myBlob) => {
    myImage.src = URL.createObjectURL(myBlob);
  })
  .catch((error) => {
    console.error("There has been a problem with your fetch operation:", error);
  });

fetch() Request() request fetch()

js
const myHeaders = new Headers();

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

fetch(myRequest)
  .then((response) => response.blob())
  .then((myBlob) => {
    myImage.src = URL.createObjectURL(myBlob);
  });

Request() fetch() request

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

request response bodies stream request/response init body body body

clone() request response body clone() body body

Headers

Headers Headers() 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")); // null

ServiceWorkers Headers API

HTTP Header Headers TypeError TypeError

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

content-type

js
fetch(myRequest)
  .then((response) => {
    const contentType = response.headers.get("content-type");
    if (!contentType || !contentType.includes("application/json")) {
      throw new TypeError("Oops, we haven't got JSON!");
    }
    return response.json();
  })
  .then((data) => {
    /* process your data further */
  })
  .catch((error) => console.error(error));

Guard

Headers request response Headers guard Web Headers

guard request Request Header Content-Length Set-Cookie response header Service Worker Response cookie

Response

Response fetch() promise

response

JavaScript ServiceWorkers respondWith() response request

js
const myBody = new Blob();

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

Response() response body Request() init

error() responseredirect() URL response Service Worker

Body

body body

Body Request Response body Promise

XHR

body

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

request response fetch() Content-Type Content-Type

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

js
if (window.fetch) {
  // run my fetch request here
} else {
  // do something with XMLHttpRequest?
}


Web Proxy Viewer  |  New URL  |  Original Page