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

API - Web API | MDN

MDN Web Docs

View in English Always switch to English

API

API HTTP JavaScript

XMLHttpRequest XMLHttpRequest (CORS)

API fetch() Request URL

fetch() Promise Response JSON

fetch() JSON

js
async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`: ${response.status}`);
    }

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

URL fetch() URL

fetch() 404 OK throw

Response json() JSON fetch() json()

fetch()

fetch()

fetch() GET method

js
const response = await fetch("https://example.org/post", {
  method: "POST",
  // 
});

mode no-cors method GETPOSTHEAD

GET POST PUT POST

body

js
const response = await fetch("https://example.org/post", {
  method: "POST",
  body: JSON.stringify({ username: "example" }),
  // 
});

toString() URLSearchParams

js
const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  //  "username=example&password=password" 
  body: new URLSearchParams({ username: "example", password: "password" }),
  // 
});

2

js
const request = new Request("https://example.org/post", {
  method: "POST",
  body: JSON.stringify({ username: "example" }),
});

const response1 = await fetch(request);
console.log(response1.status);

// : "Body has already been consumed."
const response2 = await fetch(request);
console.log(response2.status);

js
const request1 = new Request("https://example.org/post", {
  method: "POST",
  body: JSON.stringify({ username: "example" }),
});

const request2 = request1.clone();

const response1 = await fetch(request1);
console.log(response1.status);

const response2 = await fetch(request2);
console.log(response2.status);

POST Content-Type

headers

:

js
const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ username: "example" }),
  // 
});

Headers Headers.append() Headers headers

js
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: myHeaders,
  body: JSON.stringify({ username: "example" }),
  // 
});

Headers mode no-cors

GET

GET URL URLSearchParams URL

js
const params = new URLSearchParams();
params.append("username", "example");

// GET  https://example.org/login?username=example 
const response = await fetch(`https://example.org/login?${params}`);

RequestInit.mode corssame-originno-cors 3

RequestInit.mode

API

Set-Cookie credentials 3

  • omit:
  • same-origin :
  • include:

SameSite Strict Lax credentials include

credentials include Access-Control-Allow-Credentials Access-Control-Allow-Origin *

credentials include

Request

Request() fetch() fetch() Request() fetch()

fetch() POST

js
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

const response = await fetch("https://example.org/post", {
  method: "POST",
  body: JSON.stringify({ username: "example" }),
  headers: myHeaders,
});

Request()

js
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

const myRequest = new Request("https://example.org/post", {
  method: "POST",
  body: JSON.stringify({ username: "example" }),
  headers: myHeaders,
});

const response = await fetch(myRequest);

2

js
async function post(request) {
  try {
    const response = await fetch(request);
    const result = await response.json();
    console.log(":", result);
  } catch (error) {
    console.error(":", error);
  }
}

const request1 = new Request("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ username: "example1" }),
});

const request2 = new Request(request1, {
  body: JSON.stringify({ username: "example2" }),
});

post(request1);
post(request2);

AbortController AbortSignal signal

abort() fetch() AbortError

js
const controller = new AbortController();

const fetchButton = document.querySelector("#fetch");
fetchButton.addEventListener("click", async () => {
  try {
    console.log("");
    const response = await fetch("https://example.org/get", {
      signal: controller.signal,
    });
    console.log(`: ${response.status}`);
  } catch (e) {
    console.error(`: ${e}`);
  }
});

const cancelButton = document.querySelector("#cancel");
cancelButton.addEventListener("click", () => {
  controller.abort();
  console.log("");
});

fetch() AbortError

js
async function get() {
  const controller = new AbortController();
  const request = new Request("https://example.org/get", {
    signal: controller.signal,
  });

  const response = await fetch(request);
  controller.abort();
  //  `AbortError` 
  const text = await response.text();
  console.log(text);
}

fetch() Response

fetch() 404 fetch() Response

Response.status Response.ok 200 true

ok false

js
async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`: ${response.status}`);
    }
    // 
  } catch (error) {
    console.error(error.message);
  }
}

type

  • basic:
  • cors: CORS
  • opaque: no-cors
  • opaqueredirect: redirect manual

  • CORS CORS

  • status 0 null

headers Headers

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 ");
    }
    //  JSON 
  } catch (error) {
    console.error(":", error);
  }
}

Response

Promise

Blob URL

js
const image = document.querySelector("img");

const url = "flowers.jpg";

async function setImage() {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`: ${response.status}`);
    }
    const blob = await response.blob();
    const objectURL = URL.createObjectURL(blob);
    image.src = objectURL;
  } catch (e) {
    console.error(e);
  }
}

JSON json()

ReadableStream json()

GET

js
const url = "https://www.example.org/a-large-file.txt";

async function fetchText(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`: ${response.status}`);
    }

    const text = await response.text();
    console.log(text);
  } catch (e) {
    console.error(e);
  }
}

Response.text()

js
const url = "https://www.example.org/a-large-file.txt";

async function fetchTextAsStream(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`: ${response.status}`);
    }

    const stream = response.body.pipeThrough(new TextDecoderStream());
    for await (const value of stream) {
      console.log(value);
    }
  } catch (e) {
    console.error(e);
  }
}

iterate asynchronously

ReadableStream.pipeThrough() TextDecoderStream UTF-8

1

UTF-8

js
async function* makeTextFileLineIterator(fileURL) {
  const response = await fetch(fileURL);
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();

  let { value: chunk = "", done: readerDone } = await reader.read();

  const newline = /\r?\n/g;
  let startIndex = 0;

  while (true) {
    const result = newline.exec(chunk);
    if (!result) {
      if (readerDone) break;
      const remainder = chunk.slice(startIndex);
      ({ value: chunk, done: readerDone } = await reader.read());
      chunk = remainder + (chunk || "");
      startIndex = newline.lastIndex = 0;
      continue;
    }
    yield chunk.substring(startIndex, result.index);
    startIndex = newline.lastIndex;
  }

  if (startIndex < chunk.length) {
    // 
    yield chunk.substring(startIndex);
  }
}

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

function processLine(line) {
  console.log(line);
}

run("https://www.example.org/a-large-file.txt");

  • ReadableStream.getReader()

js
async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`: ${response.status}`);
    }

    const result1 = await response.json();
    const result2 = await response.json(); // 
  } catch (error) {
    console.error(error.message);
  }
}

Response.clone()

js
async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response1 = await fetch(url);
    if (!response1.ok) {
      throw new Error(`: ${response1.status}`);
    }

    const response2 = response1.clone();

    const result1 = await response1.json();
    const result2 = await response2.json();
  } catch (error) {
    console.error(error.message);
  }
}

js
async function cacheFirst(request) {
  const cachedResponse = await caches.match(request);
  if (cachedResponse) {
    return cachedResponse;
  }
  try {
    const networkResponse = await fetch(request);
    if (networkResponse.ok) {
      const cache = await caches.open("MyCache_1");
      cache.put(request, networkResponse.clone());
    }
    return networkResponse;
  } catch (error) {
    return Response.error();
  }
}

self.addEventListener("fetch", (event) => {
  if (precachedResources.includes(url.pathname)) {
    event.respondWith(cacheFirst(event.request));
  }
});


Web Proxy Viewer  |  New URL  |  Original Page