fetch用法

Fetch API

Fetch API提供了一個fetch()方法,它被定義在BOM的window對象中,你可以用它來發(fā)起對遠程資源的請求。 該方法返回的是一個Promise對象,讓你能夠?qū)φ埱蟮姆祷亟Y果進行檢索。

為什么使用Fetch

傳統(tǒng)ajax,必須使用它的實例來執(zhí)行請求和接收返回響應。
通過FetchAPI可以明確配置請求對象。

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
一個Requeset對象

options(可選)

一個配置項對象,包括所有對請求的設置??蛇x參數(shù)有:
method:請求使用的方法,如GET、POST。
headers:請求的頭信息,形式為Headers對象ByteString。
body:請求的body信息:可能是一個Blob、BufferSource、FormData、URLSearchParams
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請求結果參數(shù),在100–599 范圍
? ? ? statusText (String)- 服務器返回的狀態(tài)報告
? ? ? ok (boolean)- 如果返回200表示請求成功則為true
? ? ? headers (Headers)- 返回頭部信息,下面詳細介紹
? ? ? url (String)- 請求的地址
方法:
? ? ? text()- 以string的形式生成請求text
? ? ? json()- 生成JSON.parse(responseText)的結果
? ? ? blob()- 生成一個Blob
? ? ? arrayBuffer()- 生成一個ArrayBuffer
? ? ? formData()- 生成格式化的數(shù)據(jù),可用于其他的請求
其他方法:
? ? ? clone()
? ? ? Response.error()
? ? ? Response.redirect()
response.headers
has(name) (boolean)- 判斷是否存在該信息頭
get(name) (String)- 獲取信息頭的數(shù)據(jù)
getAll(name) (Array)- 獲取所有頭部數(shù)據(jù)
set(name, value)- 設置信息頭的參數(shù)
append(name, value)- 添加header的內(nèi)容
delete(name)- 刪除header的信息
forEach(function(value, name){ ... }, [thisContext])- 循環(huán)讀取header的信息

GET請求

fetch('/users.html')?
.then(function(response){
? ? returnresponse.text()?
}).then(function(body){
? ? document.body.innerHTML = body?
})

POST請求

fetch('/users', {
? ?method:'POST',
? ?headers: {
? ? ? ? 'Accept':'application/json',
? ? ? ? 'ContentType':'application/json'
? ?},
? body: JSON.stringify({
? ? ? ?name:'Yancy',
? ? ? ?login:'Yancy',?
? })
})

采用promise形式

var promise =new Promise(function(resolve, reject){
? if(/* 異步操作成功 */){
? ? resolve(value);?
? }else{
? ? reject(error);?
?}
});

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容