LoginSignup
4
10

More than 3 years have passed since last update.

Javascriptのfetch

Last updated at Posted at 2020-08-04

初心者が解説のサイトなどを見て、Javascriptのfetch()を理解しようとしています。

参考 fetch() の基本的な使い方

  • fetch() メソッドは従来の XMLHttpRequest や jQuery の $.ajax() を使って実現していたような、 リモートリソースの非同期取り込みに使える
  • 非同期呼び出しは Promise で実装されていて、then() で Response オブジェクトを受け取
  • ネットワークエラー以外は、基本的に最初の then() まで到達します。最初の then((response)) で response.ok や response.status をチェックすることで、サーバー側からの応答の状態を確認できます。
  • エラーを検出したら、Error() オブジェクトをスローすることで、catch() に処理が移る

Fetchの利用
- サービスワーカーのような他の技術から簡単に利用することができます。 Fetch は CORS や HTTP 拡張のような HTTP に関連する概念をまとめて定義する場所でもあります。


fetch('http://...',{オプション})
.then((response)=>{
  if(!response.ok){
    throw new Error();
  }
  return response.blob();//あるいは response.json()
})
.then((blob)=>{

})
.catch((reason)=>{
  //エラー
});

fetch() による GET リクエストの送信

fetch('/test1')
  .then((res) => {
      if (!res.ok) {
          throw new Error(`${res.status} ${res.statusText}`);
      }
      return res.blob();
  })
  .then((blob) => {
      // ...
  })
  .catch((reason) => {
      console.log(reason);
  });
fetch() による POST リクエス

fetch() による POST リクエストの送信

const data = new FormData();
data.set('message', 'Hello!');

fetch('/test',
    {
        method: 'POST',
        cache: 'no-cache',
        body: data
    })
    .then((res) => {
        if (!res.ok) {
            throw new Error(`${res.status} ${res.statusText}`);
        }
        return res.blob();
    })
    .then((blob) => {
      // blob にレスポンスデータが入る
    })
    .catch((reason) => {
        console.log(reason);
    });

JSON文字列をポストする場合
const data = {
    message: 'Hello'
};

fetch('/test',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then((res) => {
        if (!res.ok) {
            throw new Error(`${res.status} ${res.statusText}`);
        }
        return res.blob();
    })
    .then((blob) => {
        // blob にデータが入る
    })
    .catch((reason) => {
        console.log(reason);
    });

?やばい、よくわからない

  • 最初の then((response)) にて、return response.blob() とすることで、 レスポンスの内容を Blob オブジェクトに詰め込んで、次の then() に渡すことができます。

Blobオブジェクトとは:

  • fetch() から返される Promise は レスポンスが HTTP 404 や 500 を返して HTTP エラーステータスの場合でも拒否されません。代わりに (ok ステータスが false にセットされて) 正常に解決し、拒否されるのはネットワークのエラーや、何かがリクエストの完了を妨げた場合のみです。
  • fetch() はサイトをまたぐクッキーを受け付けません受信することができます。フェッチを使用してサイトをまたぐセッションを確立することができませんできます。他のサイトからの Set-Cookie ヘッダーは暗黙に無視されます。
  • fetch はサーバーとの間で cookies を送受信しないため、サイトがユーザーセッションの維持に頼っている場合は未認証のリクエストになります。クッキーを送るには、認証情報の init オプションを設定しておく必要があります。
簡単な例
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data=>consol.elog(data));

参考
これを実際に使ってみたら何となく理解できたような気がする

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>サンプル</title>
</head>
<body >

<input type="button" value="ボタン1" onclick="clickBtn1()">
<input type="text" name="cs1" id="cs1" value="custom1" maxlength="7">
<input type="text" name="cs2" id="cs2" value="custom2" maxlength="7">

<script>
function clickBtn1(){
    // URLSearchParamsに画面の値をセット
    const para1 = new URLSearchParams();
    para1.set("cs1",document.getElementById("cs1").value);
    para1.set("cs2",document.getElementById("cs2").value);

    fetch("http://httpbin.org/get?" + para1.toString())

        .then(function(response1) { //成功時に実行される
            console.log("status=" + response1.status); //status=200
            return response1.json();
        })
        .then(function(data1) { //成功時に実行される
            console.log(JSON.stringify(data1)); //JSONを出力
        })
        .catch(function(err1) { //失敗時に実行される
            console.log("err=" + err1);
        });
}
</script>
</body>
</html>

Service WorkersではこのFetch APIを使うことになっている

お疲れさまXMLHttpRequest、こんにちはfetch

Service Workersでは、XMLHttpRequestが使えません。その代わり、XMLHttpRequest (以下、XHR)に代わるWHATWGの仕様としてFetch APIがあり、Service WorkersではこのFetch APIを使うことになっていますので、その使い方を簡単に紹介します。

Fetch API自体は、Service Workers専用のものではなく、メインスレッドでもXHRの代わりに使うことが可能です。


fetch('URLあるいは相対パスなど').then(...);
4
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
10