【譯】fetch用法說明

因爲 FetchAPI 是基於 Promise 設計,有必要先學習一下 Promise,推薦閱讀 MDN Promise 教程
本文章內容推薦閱讀 MDN Fetch 教程html

語法說明

fetch(url, options).then(function(response) {
  // handle HTTP response
}, function(error) {
  // handle network error
})

具體參數案例:java

//兼容包
require('babel-polyfill')
require('es6-promise').polyfill()

import 'whatwg-fetch'

fetch(url, {
  method: "POST",
  body: JSON.stringify(data),
  headers: {
    "Content-Type": "application/json"
  },
  credentials: "same-origin"
}).then(function(response) {
  response.status     //=> number 100–599
  response.statusText //=> String
  response.headers    //=> Headers
  response.url        //=> String

  response.text().then(function(responseText) { ... })
}, function(error) {
  error.message //=> String
})

url

定義要獲取的資源。這多是:git

  • 一個 USVString 字符串,包含要獲取資源的 URLes6

  • 一個 Request 對象。github

options(可選)

一個配置項對象,包括全部對請求的設置。可選的參數有:json

  • method: 請求使用的方法,如 GETPOSTpromise

  • headers: 請求的頭信息,形式爲 Headers 對象或 ByteString服務器

  • body: 請求的 body 信息:多是一個 BlobBufferSourceFormDataURLSearchParams 或者 USVString 對象。注意 GETHEAD 方法的請求不能包含 body 信息。babel

  • mode: 請求的模式,如 corsno-cors 或者 same-originapp

  • credentials: 請求的 credentials,如 omitsame-origin 或者 include

  • cache: 請求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached

response

一個 Promiseresolve 時回傳 Response 對象:

  • 屬性:

    • status (number) - HTTP請求結果參數,在100–599 範圍

    • statusText (String) - 服務器返回的狀態報告

    • ok (boolean) - 若是返回200表示請求成功則爲true

    • headers (Headers) - 返回頭部信息,下面詳細介紹

    • url (String) - 請求的地址

  • 方法:

    • text() - 以string的形式生成請求text

    • json() - 生成JSON.parse(responseText)的結果

    • blob() - 生成一個Blob

    • arrayBuffer() - 生成一個ArrayBuffer

    • formData() - 生成格式化的數據,可用於其餘的請求

  • 其餘方法:

    • clone()

    • Response.error()

    • Response.redirect()

response.headers

  • has(name) (boolean) - 判斷是否存在該信息頭

  • get(name) (String) - 獲取信息頭的數據

  • getAll(name) (Array) - 獲取全部頭部數據

  • set(name, value) - 設置信息頭的參數

  • append(name, value) - 添加header的內容

  • delete(name) - 刪除header的信息

  • forEach(function(value, name){ ... }, [thisContext]) - 循環讀取header的信息

使用案例

GET請求

  • HTML

    fetch('/users.html')
      .then(function(response) {
        return response.text()
      }).then(function(body) {
        document.body.innerHTML = body
      })
  • IMAGE

    var myImage = document.querySelector('img');
    
    fetch('flowers.jpg')
      .then(function(response) {
        return response.blob();
      })
      .then(function(myBlob) {
        var objectURL = URL.createObjectURL(myBlob);
        myImage.src = objectURL;
      });
  • JSON

    fetch(url)
      .then(function(response) {
        return response.json();
      }).then(function(data) {
        console.log(data);
      }).catch(function(e) {
        console.log("Oops, error");
      });

使用 ES6 的 箭頭函數 後:

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

response的數據

fetch('/users.json').then(function(response) {
  console.log(response.headers.get('Content-Type'))
  console.log(response.headers.get('Date'))
  console.log(response.status)
  console.log(response.statusText)
})

POST請求

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})

檢查請求狀態

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

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

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })

採用promise形式

Promise 對象是一個返回值的代理,這個返回值在promise對象建立時未必已知。它容許你爲異步操做的成功或失敗指定處理方法。 這使得異步方法能夠像同步方法那樣返回值:異步方法會返回一個包含了原返回值的 promise 對象來替代原返回值。

Promise構造函數接受一個函數做爲參數,該函數的兩個參數分別是resolve方法和reject方法。若是異步操做成功,則用resolve方法將Promise對象的狀態變爲「成功」(即從pending變爲resolved);若是異步操做失敗,則用reject方法將狀態變爲「失敗」(即從pending變爲rejected)。

promise實例生成之後,能夠用then方法分別指定resolve方法和reject方法的回調函數。

//建立一個promise對象
var promise = new Promise(function(resolve, reject) {
  if (/* 異步操做成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});
//then方法能夠接受兩個回調函數做爲參數。
//第一個回調函數是Promise對象的狀態變爲Resolved時調用,第二個回調函數是Promise對象的狀態變爲Reject時調用。
//其中,第二個函數是可選的,不必定要提供。這兩個函數都接受Promise對象傳出的值做爲參數。
promise.then(function(value) {
  // success
}, function(value) {
  // failure
});

那麼結合promise後fetch的用法:

//Fetch.js
export function Fetch(url, options) {
  options.body = JSON.stringify(options.body)

  const defer = new Promise((resolve, reject) => {
    fetch(url, options)
      .then(response => {
        return response.json()
      })
      .then(data => {
        if (data.code === 0) {
          resolve(data) //返回成功數據
        } else {
            if (data.code === 401) {
            //失敗後的一種狀態
            } else {
            //失敗的另外一種狀態
            }
          reject(data) //返回失敗數據
        }
      })
      .catch(error => {
        //捕獲異常
        console.log(error.msg)
        reject() 
      })
  })

  return defer
}

調用Fech方法:

import { Fetch } from './Fetch'

Fetch(getAPI('search'), {
  method: 'POST',
  options
})
.then(data => {
  console.log(data)
})

支持情況及解決方案

原生支持率並不高,幸運的是,引入下面這些 polyfill 後能夠完美支持 IE8+ :

  • 因爲 IE8 是 ES3,須要引入 ES5 的 polyfill: es5-shim, es5-sham

  • 引入 Promisepolyfill: es6-promise

  • 引入 fetch 探測庫:fetch-detector

  • 引入 fetchpolyfill: fetch-ie8

  • 可選:若是你還使用了 jsonp,引入 fetch-jsonp

  • 可選:開啓 Babelruntime 模式,如今就使用 async/await

翻譯自 Fetch

相關文章
相關標籤/搜索