一文秒懂 ajax, fetch, axios

2019-10-29    seo達(dá)人

1, JavaScript的Ajax

Ajax的全稱是Asynchronous JavaScript and XML,意思就是用JavaScript執(zhí)行異步網(wǎng)絡(luò)請(qǐng)求,而不需要重載(刷新)整個(gè)頁面。

Ajax使用XMLHttpRequest對(duì)象取得新數(shù)據(jù),然后再通過 DOM 將新數(shù)據(jù)插入到頁面中。另外,雖然名字中包含 XML 的成分,但 Ajax 通信與數(shù)據(jù)格式無關(guān); 這種技術(shù)就是無須刷新頁面即可從服務(wù)器取得數(shù)據(jù),但不一定是 XML 數(shù)據(jù)。

對(duì)于IE7+和其他瀏覽器,可以直接使用XMLHttpRequest對(duì)象,對(duì)于IE6及以前的瀏覽器,使用ActiveXObject對(duì)象。



使用方法如下:



var xhr;

if (window.XMLHttpRequest) {

    xhr = new XMLHttpRequest();

} else {

    xhr = new ActiveXObject('Microsoft.XMLHTTP');

}

1

2

3

4

5

6

啟動(dòng)請(qǐng)求:



xhr.open(method, url, boolean);     

xhr.send();

1

2

注:

1,xhr.open參數(shù)含義:

method:請(qǐng)求方式,post、get等

url: 請(qǐng)求鏈接,只能向同源的url發(fā)送請(qǐng)求

boolean:是否異步請(qǐng)求,true:異步, false: 同步,默認(rèn)為true

2,調(diào)用 open()方法并不會(huì)真正發(fā)送請(qǐng)求, 而只是啟動(dòng)一個(gè)請(qǐng)求以備發(fā)送。

3,send()方法接收一個(gè)參數(shù),即要作為請(qǐng)求主體發(fā)送的數(shù)據(jù)(post方法會(huì)使用,get方法直接傳null)。如果不需要通過請(qǐng)求主體發(fā)送數(shù)據(jù),則必須傳入 null,因?yàn)檫@個(gè)參數(shù)對(duì)有些瀏覽器來說是必需的。調(diào)用send()之后,請(qǐng)求就會(huì)被分派到服務(wù)器。



XMLHttpRequest對(duì)象的異步請(qǐng)求示例如下:



function success(text) {

    console.log(text);

}



function fail(code) {

   console.log(code);

}



var xhr = new XMLHttpRequest();     // 新建XMLHttpRequest對(duì)象

xhr.onreadystatechange = function () { 

    // 狀態(tài)發(fā)生變化時(shí),函數(shù)被回調(diào)

    if (xhr.readyState === 4) { // 成功完成

        // 判斷響應(yīng)結(jié)果:

        if (xhr.status === 200) {

            // 成功,通過responseText拿到響應(yīng)的文本:

            return success(xhr.responseText);

        } else {

            // 失敗,根據(jù)響應(yīng)碼判斷失敗原因:

            return fail(xhr.status);

        }

    } else {

        // HTTP請(qǐng)求還在繼續(xù)...

    }

}



// 發(fā)送請(qǐng)求:

xhr.open('get', '/api/categories');

xhr.send(null);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

xhr的屬性含義如下:

responseText: 作為響應(yīng)主體被返回的文本。

responseXML: 如果響應(yīng)的內(nèi)容類型是"text/xml"或"application/xml",這個(gè)屬性中將保存響應(yīng)數(shù)據(jù)的 XML DOM 文檔。

status: 響應(yīng)的 HTTP 狀態(tài)。

statusText: HTTP 狀態(tài)的說明。

readyState :表示請(qǐng)求/響應(yīng)過程的當(dāng)前活動(dòng)階段。可取值如下。

0: 未初始化。尚未調(diào)用 open()方法。

1: 啟動(dòng)。已經(jīng)調(diào)用 open()方法,但尚未調(diào)用 send()方法。

2: 發(fā)送。已經(jīng)調(diào)用 send()方法,但尚未接收到響應(yīng)。

3: 接收。已經(jīng)接收到部分響應(yīng)數(shù)據(jù)。

4: 完成。已經(jīng)接收到全部響應(yīng)數(shù)據(jù),而且已經(jīng)可以在客戶端使用了。

只要 readyState 屬性的值由一個(gè)值變成另一個(gè)值,都會(huì)觸發(fā)一次 readystatechange 事件。可以利用這個(gè)事件來檢測每次狀態(tài)變化后readyState 的值。通常,我們只對(duì) readyState 值為 4 的階段感興趣,因?yàn)檫@時(shí)所有數(shù)據(jù)都已經(jīng)就緒。不過,必須在調(diào)用 open()之前指定 onreadystatechange事件處理程序才能確??鐬g覽器兼容性。



另外,在接收到響應(yīng)之前還可以調(diào)用 abort()方法來取消異步請(qǐng)求:



xhr.abort();

1

調(diào)用這個(gè)方法后,XHR 對(duì)象會(huì)停止觸發(fā)事件,而且也不再允許訪問任何與響應(yīng)有關(guān)的對(duì)象屬性。在終止請(qǐng)求之后,還應(yīng)該對(duì) XHR 對(duì)象進(jìn)行解引用操作。由于內(nèi)存原因,不建議重用 XHR 對(duì)象。



2, jQuery的Ajax

$.ajax({

        url:"",

        type:"GET",

        contentType: '',

        async:true,

        data:{},

        dataType:"",

        success: function(){

        }

});

1

2

3

4

5

6

7

8

9

10

url 必填項(xiàng),規(guī)定把請(qǐng)求發(fā)送到哪個(gè) URL。

type 以什么樣的方式獲取數(shù)據(jù),是get或post

contentType:發(fā)送POST請(qǐng)求的格式,默認(rèn)值為’application/x-www-form-urlencoded;

charset=UTF-8’,也可以指定為text/plain、application/json

async 是否異步執(zhí)行AJAX請(qǐng)求,默認(rèn)為true,千萬不要指定為false

data 發(fā)送的數(shù)據(jù),可以是字符串、數(shù)組或object。如果是GET請(qǐng)求,data將被轉(zhuǎn)換成query附加到URL上,如果是POST請(qǐng)求,根據(jù)contentType把data序列化成合適的格式;

dataType

接收的數(shù)據(jù)格式,可以指定為’html’、‘xml’、‘json’、'text’等,缺省情況下根據(jù)響應(yīng)的Content-Type猜測。

success 可選。執(zhí)行成功時(shí)返回的數(shù)據(jù)。

缺點(diǎn):

是基于XHR原生開發(fā)的,目前已有的fetch可替代。本身是針對(duì)mvc的編程模式,不太適合目前mvvm的編程模式。jQuery本身比較大,如果單純的使用ajax可以自己封裝一個(gè),不然會(huì)影響性能體驗(yàn)。



3,Axios

Vue2.0之后,axios開始受到更多的歡迎。其實(shí)axios也是對(duì)原生XHR的一種封裝,不過是Promise實(shí)現(xiàn)版本。它是一個(gè)用于瀏覽器和 nodejs 的 HTTP 客戶端,符合的ES規(guī)范。



axios具有以下特征:



從瀏覽器中創(chuàng)建 XMLHttpRequest

支持 Promise API

客戶端支持防止CSRF

提供了一些并發(fā)請(qǐng)求的接口

從 node.js 創(chuàng)建 http 請(qǐng)求

攔截請(qǐng)求和響應(yīng)

轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)

取消請(qǐng)求

自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)

PS:防止CSRF:就是讓你的每個(gè)請(qǐng)求都帶一個(gè)從cookie中拿到的key, 根據(jù)瀏覽器同源策略,假冒的網(wǎng)站是拿不到你cookie中得key的,這樣,后臺(tái)就可以輕松辨別出這個(gè)請(qǐng)求是否是用戶在假冒網(wǎng)站上的誤導(dǎo)輸入,從而采取正確的策略。



設(shè)置全局的 axios 默認(rèn)值



axios.defaults.baseURL = '
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

1

2

3

注:axios 的 headers的 content-type 默認(rèn)是 “application/json ”



默認(rèn)情況下,axios將JavaScript對(duì)象序列化為JSON,如果是get請(qǐng)求,對(duì)請(qǐng)求參數(shù)不用做任何處理,但是如果是post請(qǐng)求,并且Content-Type 為application/x-www-form-urlencoded,需要使用URLSearchParams API格式化請(qǐng)求參數(shù), 否則Content-Type依然是application/json



var params = new URLSearchParams();

params.append('param1', 'value1');

params.append('param2', 'value2');

1

2

3

get請(qǐng)求,以下3中寫法完全等價(jià)



axios.get('/user?id=12345&name=xiaoming')

.then(function (response) {

    console.log(response);

})

.catch(function (error) {

    console.log(error);

});

1

2

3

4

5

6

7

axios.get('/user', {

    params: {

      id: '12345',

      name: 'xiaoming'

    }

})

.then(function (response) {

    console.log(response);

})

.catch(function (error) {

    console.log(error);

});

1

2

3

4

5

6

7

8

9

10

11

12

axios({

    url: '/user',

    method: 'get',

    params: {

      id: '12345',

      name: 'xiaoming'

    }

})

.then(function (response) {

    console.log(response);

})

.catch(function (error) {

    console.log(error);

});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

post請(qǐng)求,以下2種寫法完全等價(jià)



axios({

    url: '/user',

    method: 'post',

    headers: {

        'Content-Type': 'application/json'

    },

    data: {

      id: '12345',

      name: 'xiaoming'

    }

})

.then(function (response) {

    console.log(response);

})

.catch(function (error) {

    console.log(error);

});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

var url = '/user';

var data = {

      id: '12345',

      name: 'xiaoming'

    };

axios.post(url, data, {

       headers: {

        'Content-Type': 'application/json'

    }

})

.then(function (response) {

    console.log(response);

})

.catch(function (error) {

    console.log(error);

});

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

執(zhí)行多個(gè)并發(fā)請(qǐng)求



function getUserAccount() {

  return axios.get('/user/12345');

}

 

function getUserPermissions() {

  return axios.get('/user/12345/permissions');

}

 

axios.all([getUserAccount(), getUserPermissions()])

  .then(axios.spread(function (acct, perms) {

    // 兩個(gè)請(qǐng)求現(xiàn)在都執(zhí)行完成

}));

1

2

3

4

5

6

7

8

9

10

11

12

創(chuàng)建實(shí)例



可以使用自定義配置新建一個(gè) axios 實(shí)例



axios.create([config])

var instance = axios.create({

  baseURL: '

  timeout: 1000,

  headers: {'X-Custom-Header': 'foobar'}

});

1

2

3

4

5

6

配置會(huì)以一個(gè)優(yōu)先順序進(jìn)行合并,順序由低到高為

1,在 node_modules/axios/lib/defaults.js 找到的庫的默認(rèn)值

2,實(shí)例的 defaults 屬性

3,請(qǐng)求的 config 參數(shù)



// 使用由庫提供的配置的默認(rèn)值來創(chuàng)建實(shí)例

// 此時(shí)超時(shí)配置的默認(rèn)值是 0

var instance = axios.create();

 

// 覆寫庫的超時(shí)默認(rèn)值

// 現(xiàn)在,所有請(qǐng)求都會(huì)等待 2.5 秒

instance.defaults.timeout = 2500;

 

// 為已知需要花費(fèi)很長時(shí)間的請(qǐng)求覆寫超時(shí)設(shè)置

instance.get('/longRequest', {

  timeout: 5000

});

1

2

3

4

5

6

7

8

9

10

11

12

攔截器



在請(qǐng)求發(fā)出之前或響應(yīng)被 then 或 catch 處理前攔截它們做預(yù)處理。



// 添加請(qǐng)求攔截器

axios.interceptors.request.use(function (config) {

    // 在發(fā)送請(qǐng)求之前做些什么

  }, function (error) {

    // 對(duì)請(qǐng)求錯(cuò)誤做些什么

  });

 

// 添加響應(yīng)攔截器

axios.interceptors.response.use(function (response) {

    // 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么

  }, function (error) {

    // 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么

  });

1

2

3

4

5

6

7

8

9

10

11

12

13

可以在稍后移除攔截器:



var myInterceptor = axios.interceptors.request.use(function () {/.../});

axios.interceptors.request.eject(myInterceptor);

1

2

可以為自定義 axios 實(shí)例添加攔截器



var instance = axios.create();

instance.interceptors.request.use(function () {/.../});

1

2

4, fetch

window 自帶了 window.fetch 方法, 在版的 Firefox 和 Chrome 中已經(jīng)提供支持,其他瀏覽器還有兼容性問題,要做兼容性處理。fetch 是一個(gè) 基于promise設(shè)計(jì)的low-level API,不是ajax的進(jìn)一步封裝,而是原生js,它注定不會(huì)像你習(xí)慣的 $.ajax 或是 axios 等庫幫你封裝各種各樣的功能或?qū)崿F(xiàn).



interface GlobalFetch {

    fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;

}

1

2

3

fetch()是一個(gè)全局的函數(shù),返回一個(gè)promise對(duì)象。它有兩個(gè)參數(shù),第一個(gè)參數(shù)是請(qǐng)求的地址,第二個(gè)參數(shù)是可選,RequestInit是個(gè)對(duì)象格式如下:



interface RequestInit {

    body?: any;

    cache?: RequestCache;

    credentials?: RequestCredentials;

    headers?: HeadersInit;

    integrity?: string;

    keepalive?: boolean;

    method?: string;

    mode?: RequestMode;

    redirect?: RequestRedirect;

    referrer?: string;

    referrerPolicy?: ReferrerPolicy;

    window?: any;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

優(yōu)點(diǎn):

符合關(guān)注分離,沒有將輸入、輸出和用事件來跟蹤的狀態(tài)混雜在一個(gè)對(duì)象里

更好更方便的寫法

更加底層,提供的API豐富

脫離了XHR,是ES規(guī)范里新的實(shí)現(xiàn)方式

fetch中可以設(shè)置mode為"no-cors"(不跨域)



缺點(diǎn):

fetch不支持同步請(qǐng)求

fetch只對(duì)網(wǎng)絡(luò)請(qǐng)求報(bào)錯(cuò),對(duì)400,500都當(dāng)做成功的請(qǐng)求,需要封裝去處理

fetch默認(rèn)不會(huì)帶cookie,需要添加配置項(xiàng)

fetch不支持abort,不支持超時(shí)控制,使用setTimeout及Promise.reject的實(shí)現(xiàn)的超時(shí)控制并不能阻止請(qǐng)求過程繼續(xù)在后臺(tái)運(yùn)行,造成了流量的浪費(fèi)

fetch沒有辦法原生監(jiān)測請(qǐng)求的進(jìn)度,而XHR可以



fetch的使用示例:



window.fetch(url)

    .then(response => {

        if (response.ok) {

            //通過 response 原型上的 json 方法將 response.body 轉(zhuǎn)換為 JS 對(duì)象,再返回出去

            return response.json();

        }

    }

).then(result => {

    console.log(result);

}).catch(error => {

    console.log(error);

})

1

2

3

4

5

6

7

8

9

10

11

12

需要注意以下幾點(diǎn):

1,用 response.ok判斷fetch請(qǐng)求是否成功

2,服務(wù)端只返回了response對(duì)象,而真正的請(qǐng)求結(jié)果,即 response.body,則是一個(gè) ReadableStream。fetch 將 response.body 設(shè)計(jì)成 ReadableStream 在請(qǐng)求大體積文件時(shí)變得非常有用。然而,在我們的日常使用中,還是短小的 JSON 片段更加常見。而為了兼容不常見的設(shè)計(jì),我們不得不多一次 response.json() 的調(diào)用。不僅是調(diào)用變得麻煩,如果你的服務(wù)端采用了嚴(yán)格的 REST 風(fēng)格,對(duì)于某些特殊情況并沒有返回 JSON 字符串,而是用了 HTTP 狀態(tài)碼(如:204 No Content),那么在調(diào)用 response.json() 時(shí)則會(huì)拋出異常。

3,Response 限制了響應(yīng)內(nèi)容的重復(fù)讀取和轉(zhuǎn)換,response .json / response.text 方法只能使用一個(gè)并且只能使用一次,同時(shí)使用兩個(gè),或使用兩次都會(huì)報(bào)如下錯(cuò)誤:



Uncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream is locked

1

為什么不能使用兩次?

因?yàn)閿?shù)據(jù)流只能讀取一次,一旦讀取,數(shù)據(jù)流變空,再次讀取會(huì)報(bào)錯(cuò)。

————————————————

版權(quán)聲明:本文為CSDN博主「Sherry慈」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。

原文鏈接:
https://blog.csdn.net/weixin_41480546/article/details/102805864

分享本文至:

日歷

鏈接

個(gè)人資料

存檔