fetch()函數(shù)說明與使用方法詳解
Fetch() 是 window.fetch 的 JavaScript polyfill。
全局 fetch()
函數(shù)是 web 請(qǐng)求和處理響應(yīng)的簡(jiǎn)單方式,不使用 XMLHttpRequest。這個(gè) polyfill 編寫的接近標(biāo)準(zhǔn)的 Fetch 規(guī)范。
fetch()是XMLHttpRequest的升級(jí)版,用于在JavaScript腳本里面發(fā)出 HTTP 請(qǐng)求。
fetch()的功能與 XMLHttpRequest 基本相同,但有三個(gè)主要的差異。
(1)fetch()使用 Promise,不使用回調(diào)函數(shù),因此大大簡(jiǎn)化了寫法,寫起來更簡(jiǎn)潔。
(2)采用模塊化設(shè)計(jì),API 分散在多個(gè)對(duì)象上(Response 對(duì)象、Request 對(duì)象、Headers 對(duì)象),更合理一些;相比之下,XMLHttpRequest 的 API 設(shè)計(jì)并不是很好,輸入、輸出、狀態(tài)都在同一個(gè)接口管理,容易寫出非常混亂的代碼
(3)fetch()通過數(shù)據(jù)流(Stream 對(duì)象)處理數(shù)據(jù),可以分塊讀取,有利于提高網(wǎng)站性能表現(xiàn),減少內(nèi)存占用,對(duì)于請(qǐng)求大文件或者網(wǎng)速慢的場(chǎng)景相當(dāng)有用。XMLHTTPRequest 對(duì)象不支持?jǐn)?shù)據(jù)流,
所有的數(shù)據(jù)必須放在緩存里,不支持分塊讀取,必須等待全部拿到后,再一次性吐出來。在用法上接受一個(gè) URL 字符串作為參數(shù),默認(rèn)向該網(wǎng)址發(fā)出 GET 請(qǐng)求,返回一個(gè) Promise 對(duì)象
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定義要獲取的資源。
這可能是:
• 一個(gè) USVString 字符串,包含要獲取資源的 URL。
• 一個(gè) Request 對(duì)象。
options(可選)
一個(gè)配置項(xiàng)對(duì)象,包括所有對(duì)請(qǐng)求的設(shè)置??蛇x的參數(shù)有:
• method: 請(qǐng)求使用的方法,如 GET、POST。
• headers: 請(qǐng)求的頭信息,形式為 Headers 對(duì)象或 ByteString。
• body: 請(qǐng)求的 body 信息:可能是一個(gè) Blob、BufferSource、FormData、URLSearchParams 或者 USVString 對(duì)象。注意 GET 或 HEAD 方法的請(qǐng)求不能包含 body 信息。
• mode: 請(qǐng)求的模式,如 cors、 no-cors 或者 same-origin。
• credentials: 請(qǐng)求的 credentials,如 omit、same-origin 或者 include。
• cache: 請(qǐng)求的 cache 模式: default, no-store, reload, no-cache, force-cache, 或者 only-if-cached。
2.response一個(gè) Promise,resolve 時(shí)回傳 Response 對(duì)象:
• 屬性:
o status (number) - HTTP請(qǐng)求結(jié)果參數(shù),在100–599 范圍
o statusText (String) - 服務(wù)器返回的狀態(tài)報(bào)告
o ok (boolean) - 如果返回200表示請(qǐng)求成功則為true
o headers (Headers) - 返回頭部信息,下面詳細(xì)介紹
o url (String) - 請(qǐng)求的地址
• 方法:
o text() - 以string的形式生成請(qǐng)求text
o json() - 生成JSON.parse(responseText)的結(jié)果
o blob() - 生成一個(gè)Blob
o arrayBuffer() - 生成一個(gè)ArrayBuffer
o formData() - 生成格式化的數(shù)據(jù),可用于其他的請(qǐng)求
• 其他方法:
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請(qǐng)求
• 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請(qǐng)求
fetch('/users', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Hubot', login: 'hubot', }) })
檢查請(qǐng)求狀態(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 對(duì)象是一個(gè)返回值的代理,這個(gè)返回值在promise對(duì)象創(chuàng)建時(shí)未必已知。它允許你為異步操作的成功或失敗指定處理方法。 這使得異步方法可以像同步方法那樣返回值:異步方法會(huì)返回一個(gè)包含了原返回值的 promise 對(duì)象來替代原返回值。
Promise構(gòu)造函數(shù)接受一個(gè)函數(shù)作為參數(shù),該函數(shù)的兩個(gè)參數(shù)分別是resolve方法和reject方法。如果異步操作成功,則用resolve方法將Promise對(duì)象的狀態(tài)變?yōu)?ldquo;成功”(即從pending變?yōu)閞esolved);如果異步操作失敗,則用reject方法將狀態(tài)變?yōu)?ldquo;失敗”(即從pending變?yōu)閞ejected)。
promise實(shí)例生成以后,可以用then方法分別指定resolve方法和reject方法的回調(diào)函數(shù)。
//創(chuàng)建一個(gè)promise對(duì)象 var promise = new Promise(function(resolve, reject) { if (/* 異步操作成功 */){ resolve(value); } else { reject(error); } }); //then方法可以接受兩個(gè)回調(diào)函數(shù)作為參數(shù)。 //第一個(gè)回調(diào)函數(shù)是Promise對(duì)象的狀態(tài)變?yōu)镽esolved時(shí)調(diào)用,第二個(gè)回調(diào)函數(shù)是Promise對(duì)象的狀態(tài)變?yōu)镽eject時(shí)調(diào)用。 //其中,第二個(gè)函數(shù)是可選的,不一定要提供。這兩個(gè)函數(shù)都接受Promise對(duì)象傳出的值作為參數(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) })
三:支持狀況及解決方案
原生支持率并不高,幸運(yùn)的是,引入下面這些 polyfill 后可以完美支持 IE8+ :
• 由于 IE8 是 ES3,需要引入 ES5 的 polyfill: es5-shim, es5-sham
• 引入 Promise 的 polyfill: es6-promise
• 引入 fetch 探測(cè)庫:fetch-detector
• 引入 fetch 的 polyfill: fetch-ie8
• 可選:如果你還使用了 jsonp,引入 fetch-jsonp
• 可選:開啟 Babel 的 runtime 模式,現(xiàn)在就使用 async/await
- JavaScript Fetch API請(qǐng)求和響應(yīng)攔截詳解
- JS中fetch()用法實(shí)例詳解
- 深入學(xué)習(xí)JS?XML和Fetch請(qǐng)求
- fetch跨域問題的使用詳解
- JavaScript中fetch()用法實(shí)例
- 一文掌握ajax、fetch和axios的區(qū)別對(duì)比
- JavaScript使用Fetch的方法詳解
- AJAX原理以及axios、fetch區(qū)別實(shí)例詳解
- 聊一聊數(shù)據(jù)請(qǐng)求中Ajax、Fetch及Axios的區(qū)別
- ajax和fetch的區(qū)別點(diǎn)總結(jié)
- fetch網(wǎng)絡(luò)請(qǐng)求封裝示例詳解
相關(guān)文章
實(shí)例解析JS布爾對(duì)象的toString()方法和valueOf()方法
這篇文章主要介紹了JS的布爾對(duì)象的toString()方法和valueOf()方法,是JavaScript入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-10-10了解javascript中l(wèi)et和var及const關(guān)鍵字的區(qū)別
這篇文章主要介紹了javascript中l(wèi)et和var以及const關(guān)鍵字的區(qū)別,下面我們來一起學(xué)習(xí)一下吧2019-05-05javascript之Array 數(shù)組對(duì)象詳解
本文主要是對(duì)javascript之Array 數(shù)組對(duì)象的詳解 ,比較詳細(xì),希望能給大家做一個(gè)參考。2016-06-06