Created
November 7, 2017 04:07
-
-
Save geerpm/f46cdfb2e7e43c925a95da4f5c281ed0 to your computer and use it in GitHub Desktop.
Fetch API 実用例 ref: http://qiita.com/geerpm/items/4b3ebfa91c22fb2796c5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 || "リクエストに失敗しました") | |
}) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
}) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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