fetch---基本使用

1、fetchjavascript

    fetch是一種XMLHttpRequest的一種替代方案,在工做當中除了用ajax獲取後臺數據外咱們還可使用fetch、axios來替代ajaxjava

 

2、安裝node

    

執行npm install whatwg-fetch --save便可安裝。ios

爲了兼容老版本瀏覽器,還須要安裝npm install es6-promise --savees6



3、fetch的基本使用ajax

npm install whatwg-fetch --savenpm install es6-promise --saveimport 'es6-promise'import 'whatwg-fetch'
fetch(url,options).then((res)=>{ console.log(res);},function(err){ console.log(err)})

說明:npm

    一、fetch的返回值是一個promise對象json

 

    二、optionsaxios

        method:HTTP請求方式,默認是GETapi

 

        body:請求的參數

        fetch('/xxx', {

               method: 'post',

               body:'username=zhangsan&age=17'

 

       });

 

        headers:HTTP請求頭

            由於通常使用JSON數據格式,因此設置ContentType爲application/json

 

            credentials:默認爲omit,忽略的意思,也就是不帶cookie還有兩個參數,same-origin,意思就是同源請求帶cookie;include,表示不管跨域仍是同源請求都會帶cookie

 

 

    三、在.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帶到請求中去

 

 

4、get、post請求方式

    一、get

var result = fetch('url', { credentials: 'include', headers: {            'Accept': 'application/json, text/plain, */*',        },  });

 

    二、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" });

 

5、封裝get和post方法

    一、http.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})

    二、http.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;})

 

 

6、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 

        一、從瀏覽器中建立 XMLHttpRequest

        二、從 node.js 發出 http 請求

        三、支持 Promise API

        四、攔截請求和響應

        五、轉換請求和響應數據

        六、自動轉換JSON數據

        七、客戶端支持防止CSRF/XSRF

 

fetch:

    符合關注分離,沒有將輸入、輸出和用事件來跟蹤的狀態混雜在一個對象裏

    更加底層,提供的API豐富(request, response)

    脫離了XHR,是ES規範裏新的實現方式

 

一、fetchtch只對網絡請求報錯,對400,500都當作成功的請求,須要封裝去處理

 

二、fetch默認不會帶cookie,須要添加配置項

 

三、fetch不支持abort,不支持超時控制,使用setTimeout及Promise.reject的實

現的超時控制並不能阻止請求過程繼續在後臺運行,形成了量的浪費

 

四、fetch沒有辦法原生監測請求的進度,而XHR能夠

相關文章
相關標籤/搜索