這是fetch 請求數據的方式
---fetch---基本使用
一、fetch
fetch是一種XMLHttpRequest的一種替代方案,在工作當中除了用ajax獲取后台數據外我們還可以使用fetch、axios來替代ajax
二、安裝
執行npm install whatwg-fetch --save即可安裝。
為了兼容老版本瀏覽器,還需要安裝npm install es6-promise --save
三、fetch的基本使用
npm install whatwg-fetch --save npm install es6-promise --save import 'es6-promise' import 'whatwg-fetch' fetch(url,options).then((res)=>{ console.log(res); },function(err){ console.log(err) })
說明:
1、fetch的返回值是一個promise對象
2、options
method:HTTP請求方式,默認是GET
body:請求的參數 fetch('/xxx', { method: 'post', body:'username=zhangsan&age=17' });
headers:HTTP請求頭
因為一般使用JSON數據格式,所以設置ContentType為application/json
credentials:默認為omit,忽略的意思,也就是不帶cookie還有兩個參數,same-origin,意思就是同源請求帶cookie;include,表示無論跨域還是同源請求都會帶cookie
3、在.then里面第一個回調函數中處理response
status(number): HTTP返回的狀態碼,范圍在100-599之間
statusText(String): 服務器返回的狀態文字描述
headers: HTTP請求返回頭
body: 返回體,這里有處理返回體的一些方法
text(): 將返回體處理成字符串類型
json(): 返回結果和 JSON.parse(responseText)一樣
blob(): 返回一個Blob,Blob對象是一個不可更改的類文件的二進制數據
如果請求一個XML格式文件,則調用response.text。如果請求圖片,使用response.blob方法
注意:
cookie傳遞必須在header參數里面加上credentials: 'include',才會如xhr一樣將當前cookies帶到請求中去
四、get、post請求方式
1、get
var result = fetch('url', { credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', }, });
2、post
var result = fetch('/api/post', { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, // 注意 post 時候參數的形式 body: "a=100&b=200" });
五、封裝get和post方法
1、get
import 'es6-promise' import 'whatwg-fetch' export default (url)=>({ var result = fetch(url, { credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', }, }) .then(res=>res.json()); return result })
2、post
import 'es6-promise' import 'whatwg-fetch' import qs from 'qs'; export default (url,data)=>({ var result = fetch(url, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, // 注意 post 時候參數的形式 body: qs(data) }) .then(res=>res.json()) return result; })
六、fetch與axios的區別
axios("http://xxx/xxx.json?a=123'").then((res)=>{ console.log(res)//這里的r是響應結果 }) fetch("http://www.baidu.com").then((res)=>{ console.log(res);//是一個綜合各種方法的對象,並不是請求的數據 })
fetch返回的是一個未處理的方法集合,我們可以通過這些方法得到我們想要的數據類型。如果我們想要json格式,就執行response.json(),如果我們想要字符串就response.text()
axios
1、從瀏覽器中創建 XMLHttpRequest
2、從 node.js 發出 http 請求
3、支持 Promise API
4、攔截請求和響應
5、轉換請求和響應數據
6、自動轉換JSON數據
7、客戶端支持防止CSRF/XSRF
fetch:
符合關注分離,沒有將輸入、輸出和用事件來跟蹤的狀態混雜在一個對象里
更加底層,提供的API豐富(request, response)
脫離了XHR,是ES規范里新的實現方式
1、fetchtch只對網絡請求報錯,對400,500都當做成功的請求,需要封裝去處理
2、fetch默認不會帶cookie,需要添加配置項
3、fetch不支持abort,不支持超時控制,使用setTimeout及Promise.reject的實
現的超時控制並不能阻止請求過程繼續在后台運行,造成了量的浪費
4、fetch沒有辦法原生監測請求的進度,而XHR可以