Skip to content

Instantly share code, notes, and snippets.

@geerpm
Created November 7, 2017 04:07
Show Gist options
  • Save geerpm/f46cdfb2e7e43c925a95da4f5c281ed0 to your computer and use it in GitHub Desktop.
Save geerpm/f46cdfb2e7e43c925a95da4f5c281ed0 to your computer and use it in GitHub Desktop.
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)
})
$ npm -i -S whatwg-fetch
// or
$ yarn add whatwg-fetch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment