fetch 的使用

現在應該很少有人用原生的JS內置XMLHttpRequest對象寫異步調用了,仍然用的比較多的應該是Jquery的ajax方法,例如:

$.ajax({
   type: 'get',
   url: location.herf,
   success: function(data){
       console.log(data);
   }
})

最近寫一個demo用到了fetch API,頓時覺得比ajax好用n倍,遂記錄之。

fetch 介紹

fetch API 來源于 Promise ,可參見:Promise;

fetch的API 也可以參見:fetch;

fetch()方法調用兩個參數:

fetch(input, init)

其中:
input

  • 定義要獲取的資源。這可能是:一個 USVString 字符串,包含要獲取資源的 URL。一些瀏覽器會接受 blob: 和 data:
  • 作為 schemes.一個 Request 對象。

input直白來說等于ajax中傳入的url;

fetch()另一個參數 init可以配置其他請求相關參數,相當于ajax里的type,這個參數是可選的,包括:

method: 請求使用的方法,如 GET、POST.
headers: 請求的頭信息,形式為 Headers 對象或 ByteString。
body: 請求的 body 信息,可能是一個 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 對象。(如果是 GET 或 HEAD 方法,則不能包含 body 信息)
mode: 請求的模式,如 cors、 no-cors 或者 same-origin。
credentials: 請求的 credentials,如 omit、same-origin 或者 include。
cache: 請求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached。

fetch()的success callback 是用 .then()完成的,實際上按照我的理解,fetch()就是一個Promise對象的實例,Promise對象實例如下:

new Promise(
    /* executor */
    function(resolve, reject) {...}
);
var promise = new Promise(function(resolve, reject) {
  if (/* 異步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

promise.then(function(value) {
  // success
}, function(value) {
  // failure
});

所以fetch()中,通過.then()調用異步成功函數resolve,通過.catch()調用異步失敗函數reject;
拼裝在一起,就有:

fetch(location.herf, {
    method: "get"
}).then(function(response) {
    return response.text()
}).then(function(data) {
    console.log(data)
}).catch(function(e) {
  console.log("Oops, error");
});

這其中,第一步.then()將異步數據處理為text,如果需要json數據,只需要 :

function(response) {return response.json()}

用es6箭頭函數寫,就是:

fetch(url).then(res => res.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e));

fetch 兼容性

所有的ie都不支持fetch()方法,所以,考慮兼容性,需要對fetch()使用polyfill;
使用Fetch Polyfil來實現 fetch 功能:

npm install whatwg-fetch --save

對于ie,還要引入Promise

npm install promise-polyfill --save-exact

考慮到跨域問題,需要使用Jsonp,那么還需要fetch-jsonp:

npm install fetch-jsonp

至此,則有:

import 'whatwg-fetch';
import Promise from 'promise-polyfill';
import fetchJsonp from 'fetch-jsonp';

fetchJsonp('/users.jsonp')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Ref:

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • fetch是js提供進行網絡請求的框架。 調用結構是這樣的。 fetch( url , options ).the...
    lzh_coder閱讀 500評論 0 0
  • 五十三:請解釋 JavaScript 中 this 是如何工作的。1.方法調用模式當一個函數被保存為一個對象的屬性...
    Arno_z閱讀 596評論 0 2
  • fetch已經被大部分的瀏覽器兼容了,包括chrome,Firefox,safari,opera,edge,但是I...
    風吹過的空氣閱讀 922評論 0 0
  • 本文詳細介紹了 XMLHttpRequest 相關知識,涉及內容: AJAX、XMLHTTP、XMLHttpReq...
    semlinker閱讀 13,747評論 2 18
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,969評論 19 139