fetch()函數(shù)說明與使用方法詳解
Fetch() 是 window.fetch 的 JavaScript polyfill。
全局 fetch()
函數(shù)是 web 請求和處理響應(yīng)的簡單方式,不使用 XMLHttpRequest。這個 polyfill 編寫的接近標準的 Fetch 規(guī)范。
fetch()是XMLHttpRequest的升級版,用于在JavaScript腳本里面發(fā)出 HTTP 請求。
fetch()的功能與 XMLHttpRequest 基本相同,但有三個主要的差異。
(1)fetch()使用 Promise,不使用回調(diào)函數(shù),因此大大簡化了寫法,寫起來更簡潔。
(2)采用模塊化設(shè)計,API 分散在多個對象上(Response 對象、Request 對象、Headers 對象),更合理一些;相比之下,XMLHttpRequest 的 API 設(shè)計并不是很好,輸入、輸出、狀態(tài)都在同一個接口管理,容易寫出非常混亂的代碼
(3)fetch()通過數(shù)據(jù)流(Stream 對象)處理數(shù)據(jù),可以分塊讀取,有利于提高網(wǎng)站性能表現(xiàn),減少內(nèi)存占用,對于請求大文件或者網(wǎng)速慢的場景相當有用。XMLHTTPRequest 對象不支持數(shù)據(jù)流,
所有的數(shù)據(jù)必須放在緩存里,不支持分塊讀取,必須等待全部拿到后,再一次性吐出來。在用法上接受一個 URL 字符串作為參數(shù),默認向該網(wǎng)址發(fā)出 GET 請求,返回一個 Promise 對象
fetch()函數(shù)支持所有的 HTTP 方式:
獲取HTML類型數(shù)據(jù)
fetch('/users.html') ??.then(function(response)?{ ????return?response.text() ??}).then(function(body)?{ ????document.body.innerHTML?=?body ??})
獲取JSON類型數(shù)據(jù)
fetch('/users.json') ??.then(function(response)?{ ????return?response.json() ??}).then(function(json)?{ ????console.log('parsed?json',?json) ??}).catch(function(ex)?{ ????console.log('parsing?failed',?ex) ??})
一:fetch()語法說明
fetch(url, options).then(function(response) { // handle HTTP response }, function(error) { // handle network error })
具體參數(shù)案例:
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(可選)
一個配置項對象,包括所有對請求的設(shè)置??蛇x的參數(shù)有:
• 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請求結(jié)果參數(shù),在100–599 范圍
o statusText (String) - 服務(wù)器返回的狀態(tài)報告
o ok (boolean) - 如果返回200表示請求成功則為true
o headers (Headers) - 返回頭部信息,下面詳細介紹
o url (String) - 請求的地址
• 方法:
o text() - 以string的形式生成請求text
o json() - 生成JSON.parse(responseText)的結(jié)果
o blob() - 生成一個Blob
o arrayBuffer() - 生成一個ArrayBuffer
o formData() - 生成格式化的數(shù)據(jù),可用于其他的請求
• 其他方法:
o clone()
o Response.error()
o Response.redirect()
3.response.headers
• has(name) (boolean) - 判斷是否存在該信息頭
• get(name) (String) - 獲取信息頭的數(shù)據(jù)
• getAll(name) (Array) - 獲取所有頭部數(shù)據(jù)
• set(name, value) - 設(shè)置信息頭的參數(shù)
• append(name, value) - 添加header的內(nèi)容
• delete(name) - 刪除header的信息
• forEach(function(value, name){ ... }, [thisContext]) - 循環(huán)讀取header的信息
二:具體使用案例
1.GET請求
• HTML數(shù)據(jù):
fetch('/users.html') .then(function(response) { return response.text() }).then(function(body) { document.body.innerHTML = body })
• IMAGE數(shù)據(jù)
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數(shù)據(jù)
fetch(url) .then(function(response) { return response.json(); }).then(function(data) { console.log(data); }).catch(function(e) { console.log("Oops, error"); });
使用 ES6 的 箭頭函數(shù)后:
fetch(url) .then(response => response.json()) .then(data => console.log(data)) .catch(e => console.log("Oops, error", e))
response的數(shù)據(jù)
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', }) })
檢查請求狀態(tài)
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對象創(chuàng)建時未必已知。它允許你為異步操作的成功或失敗指定處理方法。 這使得異步方法可以像同步方法那樣返回值:異步方法會返回一個包含了原返回值的 promise 對象來替代原返回值。
Promise構(gòu)造函數(shù)接受一個函數(shù)作為參數(shù),該函數(shù)的兩個參數(shù)分別是resolve方法和reject方法。如果異步操作成功,則用resolve方法將Promise對象的狀態(tài)變?yōu)?ldquo;成功”(即從pending變?yōu)閞esolved);如果異步操作失敗,則用reject方法將狀態(tài)變?yōu)?ldquo;失敗”(即從pending變?yōu)閞ejected)。
promise實例生成以后,可以用then方法分別指定resolve方法和reject方法的回調(diào)函數(shù)。
//創(chuàng)建一個promise對象 var promise = new Promise(function(resolve, reject) { if (/* 異步操作成功 */){ resolve(value); } else { reject(error); } }); //then方法可以接受兩個回調(diào)函數(shù)作為參數(shù)。 //第一個回調(diào)函數(shù)是Promise對象的狀態(tài)變?yōu)镽esolved時調(diào)用,第二個回調(diào)函數(shù)是Promise對象的狀態(tài)變?yōu)镽eject時調(diào)用。 //其中,第二個函數(shù)是可選的,不一定要提供。這兩個函數(shù)都接受Promise對象傳出的值作為參數(shù)。 promise.then(function(value) { // success }, function(value) { // failure });
那么結(jié)合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) //返回成功數(shù)據(jù) } else { if (data.code === 401) { //失敗后的一種狀態(tài) } else { //失敗的另一種狀態(tài) } reject(data) //返回失敗數(shù)據(jù) } }) .catch(error => { //捕獲異常 console.log(error.msg) reject() }) }) return defer }
調(diào)用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 模式,現(xiàn)在就使用 async/await
相關(guān)文章
實例解析JS布爾對象的toString()方法和valueOf()方法
這篇文章主要介紹了JS的布爾對象的toString()方法和valueOf()方法,是JavaScript入門學習中的基礎(chǔ)知識,需要的朋友可以參考下2015-10-10了解javascript中l(wèi)et和var及const關(guān)鍵字的區(qū)別
這篇文章主要介紹了javascript中l(wèi)et和var以及const關(guān)鍵字的區(qū)別,下面我們來一起學習一下吧2019-05-05