fetch用法说明
語法說明
fetch(url, options).then(function(response) {// handle HTTP response }, function(error) { // handle network error })具體參數案例:
//兼容包 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
定義要獲取的資源。這可能是:
-
一個?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。
response
一個?Promise,resolve?時回傳?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
-
引入?Promise?的?polyfill:?es6-promise
-
引入?fetch?探測庫:fetch-detector
-
引入?fetch?的?polyfill:?fetch-ie8
-
可選:如果你還使用了?jsonp,引入?fetch-jsonp
-
可選:開啟?Babel?的?runtime?模式,現在就使用?async/await
轉載于:https://www.cnblogs.com/dreamingbaobei/p/8315318.html
總結
- 上一篇: 回顾JAVA---1.概述及基本语法
- 下一篇: css 修改placeholder颜色