fetch使用方法

一:語法說明

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

具體參數案例:html

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
})

1.url
定義要獲取的資源。這多是:
• 一個 USVString 字符串,包含要獲取資源的 URL。
• 一個 Request 對象。
options(可選)
一個配置項對象,包括全部對請求的設置。可選的參數有:
• 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, 或者 only-if-cached。
2.response
一個 Promise,resolve 時回傳 Response 對象:
• 屬性:
o status (number) - HTTP請求結果參數,在100–599 範圍
o statusText (String) - 服務器返回的狀態報告
o ok (boolean) - 若是返回200表示請求成功則爲true
o headers (Headers) - 返回頭部信息,下面詳細介紹
o url (String) - 請求的地址
• 方法:
o text() - 以string的形式生成請求text
o json() - 生成JSON.parse(responseText)的結果
o blob() - 生成一個Blob
o arrayBuffer() - 生成一個ArrayBuffer
o formData() - 生成格式化的數據,可用於其餘的請求
• 其餘方法:
o clone()
o Response.error()
o Response.redirect()
3.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的信息es6

二:具體使用案例

1.GET請求json

• HTML:promise

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;
  });

• JSONbabel

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

使用 ES6 的 箭頭函數後:app

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

response的數據cors

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',
  })
})

檢查請求狀態async

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• 引入 Promise 的 polyfill: es6-promise• 引入 fetch 探測庫:fetch-detector• 引入 fetch 的 polyfill: fetch-ie8• 可選:若是你還使用了 jsonp,引入 fetch-jsonp• 可選:開啓 Babel 的 runtime 模式,如今就使用 async/await

相關文章
相關標籤/搜索