最近的工作过程中,在做js调取接口的时候,使用了fetch,原来是只知道fetch,但是没有怎么使用过。正好最近使用到,所以对其详细了解了下。
fetch的基本方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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() //返回一个Promise,解析成JSON,具体请看下面返回的数据 }).then(function(res){ console.log(res) //获取json数据 }).catch(function(error){ console.log(error) //请求错误时返回 })
|
返回的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| res.arrayBuffer() 读取 res对象并且将它设置为已读(因为Responses对象被设置为了 stream 的方式,所以它们只能被读取一次) ,并返回一个被解析为ArrayBuffer格式的promise对象
res.blob() 读取 res对象并且将它设置为已读(因为Responses对象被设置为了 stream 的方式,所以它们只能被读取一次) ,并返回一个被解析为Blob格式的promise对象
res.formData() 读取res对象并且将它设置为已读(因为Responses对象被设置为了 stream 的方式,所以它们只能被读取一次) ,并返回一个被解析为FormData格式的promise对象
res.json() 读取 res对象并且将它设置为已读(因为Responses对象被设置为了 stream 的方式,所以它们只能被读取一次) ,并返回一个被解析为JSON格式的promise对象
res.text() 读取 res对象并且将它设置为已读(因为Responses对象被设置为了 stream 的方式,所以它们只能被读取一次) ,并返回一个被解析为USVString格式的promise对象
|
强制带Cookie
默认情况下, fetch不会从服务端发送或接收任何 cookies, 如果站点依赖于维护一个用户会话,则导致未经认证的请求(要发送 cookies,必须发送凭据头).
1 2 3 4 5 6 7 8 9 10
| fetch(url, { method: 'GET', credentials: 'include' }) .then((res)=>{ return res.text() }) .then((res)=>{ console.log(res) })
|
原文链接: http://yoursite.com/2018/10/31/fetch的使用/
版权声明: 转载请注明出处.