新しめのChrome、Firefox、Edge、Safariで使えるService WorkersでXMLHttpRequest
の代わりとして実装された fetch()の紹介です。fetch()はPromiseで返されて、
resolve関数にはResponseオブジェクトが返されます。
🐯 Getのサンプル
url = http: fetch(url, { }).then(function(response) { return response.json(); }).then(function(json) { console.log(response.headers.get('Content-Type')); console.log(response.headers.get('Date')); console.log(response.status); console.log(response.statusText); console.log(response.type); console.log(response.url); });
|
🐝 Postのサンプル
fetch(url, { method: 'POST', body: new FormData(document.getElementById(')), headers: { Content-type: application/x-www-form-urlencoded; charset=UTF-8 } }).then(function(response) { return response.json(); }).then(function(json) { ... });
|
postするformの情報やオリジナルのheadersも追加きます。
🎂 fetchのオプション
| オプション |
値のサンプル |
| { mode: ‘cros’ } |
Cross-Origin Resource Sharing、htmlを取得したサーバ以外からAjaxでデータを取得 |
| { credentials: ‘include’ } |
認証の情報などを通信に含める |
🏀 参考リンク
🖥 VULTRおすすめ
「VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。
最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!