LoginSignup
18
15

More than 5 years have passed since last update.

Fetch API 実用例

Posted at

fetchは他ライブラリの様にエラー処理・レスポンス処理が簡素化されてないので、ちょっとしたラッパーを作ると以後、他ライブラリを使うのと同じようなレベルで扱える。


function fetchWrapper(urlString, options) {

    return fetch(urlString, options)
    .catch(err => {
      // corsエラー、networkエラー等、そもそもサーバへ本リクエストする以前のエラー
        console.log("CLIENT-ERR :", err)
      throw new Error("アクセスできません、時間を置いてお試しください")
    })
    .then(response => {
      // レスポンスのヘッダを処理したい場合はここで
      for (const pair of response.headers.entries()) {
        // console.log(" RES-HEADER: ", pair[0]+ ': '+ pair[1])
      }
      // 返り値はpromiseになってるので展開する
      const responseBodyPromise = response.json()
      return responseBodyPromise.then(body => ({ body: body, responseOk: response.ok }))
    })
    .then(({ body, responseOk }) => {
      // ここで正常なリクエスト完了だと判定
      if (responseOk) {
        return body
      }
      // サーバとのやりとりが出来ている40x系、50x系はここ
      console.log("SERVER-ERR :", body)
      throw new Error(body || "リクエストに失敗しました")
    })
}

使う

// Headers
const headers = new Headers()
headers.append("Content-Type", 'application/json')

// CORS(クロスドメイン通信)を使う場合かつCookie等をリクエストに含める場合
const corsOptions = { mode:'cors', credentials:'include' }

// Fetch API Options
let options = { headers }
// GET
options = { ...corsOptions, method:'get' }
// or POST
options = { ...corsOptions, method:'post', body:JSON.stringify(someObj) }

// Request
fetchWrapper('https://some/json', options)
.then(body => {
  // リクエスト完了
  console.log("REQUEST-SUCCESS: ", body)
  // 処理続く...
})
.catch(err => {
  // 何らかのエラーが起きた
  console.log("REQUEST-FAILED: ", err)
  alert(err.message)
})

前提

  • jsonのやりとり
  • たぶんes2015くらい
  • polyfillで未対応ブラウザへ対応する(FetchだけでなくてHeadersで必要になる場合あり)
  $ npm -i -S whatwg-fetch
  // or
  $ yarn add whatwg-fetch
18
15
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
18
15