Wiki_JS_fetchAPI - inoueshinichi/Wiki_Web GitHub Wiki

JSのfetchAPIの扱い方

参考

基本

  • fetch(Requestオブジェクト)=fetch({ url: '{Url}', options: { ... }})
const url = new URL("url");

const headers = new Headers();
headers.set("Key1", "Value1");
headers.set("Key2", "Value2");
...

const options = {
  method: "GET/POST/PUT/DELETE/OPTIONS/HEAD/TRACE/CONNECT/PATCH",
  mode: "cors/no-cors/same-origin",
  credentials: "same-origin/include/omit",
  cache: "default/no-cache/reload/force-cache/no-store/only-if-cached",
  redirect: "follow/manual/error",
  refrerrerPolicy: "no-referrer/no-referrer-when-downgrade/origin/origin-when-cross-origin/same-origin/strict-origin/strict-origin-when-cross-origin/unsafe-url",
  referrer: "about:client/空文字列/同一オリジン", // USVStringでリクエストのリファラーを指定
  integrity: {取得するリソースのハッシュ値を指定},
  headers: Headersオブジェクト,
  body: any
}

const request = new Request({ url, options });

// その1
fetch(request)
  .then((res: Response) => {
    // statement
    console.log(res); // Response
    if (res.ok) {
      return res.json(); // Promise<any>
    } else {
      return new Error("${res.statusText}: ${res.status}");
    {
  })
  .then((jsonObj: any) => {
    // statement
    const obj = jsonObj;
  })
  .catch((err: Error) => {
    // statement
    console.error(err);
  })
  .finally(() => {
    // statement
  });

// その2
async function fetching() => {
  const res: Response = await fetch(request);
  console.log(res);
  return res.json();
}

// その3
(async () => {
  const res: Response = await fetch(request);
  console.log(res);
  const data: object = await res.json();
  console.log(data);
})();

referrPolicy

  • HTTPリクエストヘッダでリファラー情報をどれだけ含めるかを制御する
項目 説明
no-referrer -
no-referrer-when-downgrade -
origin -
origin-when-cross-origin -
same-origin -
strict-origin -
strict-origin-when-cross-origin -
unsafe-url -
⚠️ **GitHub.com Fallback** ⚠️