最近的工作過(guò)程中,在做js調(diào)取接口的時(shí)候,使用了fetch,原來(lái)是只知道fetch,但是沒(méi)有怎么使用過(guò)。正好最近使用到,所以對(duì)其詳細(xì)了解了下。
fetch的基本方式
fetch(url,{
method:'GET', # 'POST','PUT','DELETE'
headers:{
'Content-Type':'application/json', //'application/x-www-form-urlencoded'
'Accept':'application/json'
},
body:JSON.stringfiy(body)
}).then((res)=>{
return res.json() //返回一個(gè)Promise,解析成JSON,具體請(qǐng)看下面返回的數(shù)據(jù)
}).then(function(res){
console.log(res) //獲取json數(shù)據(jù)
}).catch(function(error){
console.log(error) //請(qǐng)求錯(cuò)誤時(shí)返回
})
返回的數(shù)據(jù)
res.arrayBuffer()
讀取 res對(duì)象并且將它設(shè)置為已讀(因?yàn)镽esponses對(duì)象被設(shè)置為了 stream 的方式,所以它們只能被讀取一次) ,并返回一個(gè)被解析為ArrayBuffer格式的promise對(duì)象
res.blob()
讀取 res對(duì)象并且將它設(shè)置為已讀(因?yàn)镽esponses對(duì)象被設(shè)置為了 stream 的方式,所以它們只能被讀取一次) ,并返回一個(gè)被解析為Blob格式的promise對(duì)象
res.formData()
讀取res對(duì)象并且將它設(shè)置為已讀(因?yàn)镽esponses對(duì)象被設(shè)置為了 stream 的方式,所以它們只能被讀取一次) ,并返回一個(gè)被解析為FormData格式的promise對(duì)象
res.json()
讀取 res對(duì)象并且將它設(shè)置為已讀(因?yàn)镽esponses對(duì)象被設(shè)置為了 stream 的方式,所以它們只能被讀取一次) ,并返回一個(gè)被解析為JSON格式的promise對(duì)象
res.text()
讀取 res對(duì)象并且將它設(shè)置為已讀(因?yàn)镽esponses對(duì)象被設(shè)置為了 stream 的方式,所以它們只能被讀取一次) ,并返回一個(gè)被解析為USVString格式的promise對(duì)象
強(qiáng)制帶Cookie
默認(rèn)情況下, fetch不會(huì)從服務(wù)端發(fā)送或接收任何 cookies, 如果站點(diǎn)依賴于維護(hù)一個(gè)用戶會(huì)話,則導(dǎo)致未經(jīng)認(rèn)證的請(qǐng)求(要發(fā)送 cookies,必須發(fā)送憑據(jù)頭).
fetch(url, {
method: 'GET',
credentials: 'include' // 強(qiáng)制加入憑據(jù)頭
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})