自學日記

學習程式相關知識及學習法

0%

JQuery Ajax 、 Fetch 、 Axios API 介紹

JQuery Ajax 、 Fetch 、 Axios API 介紹

JQueryAjax

早期JQuery盛行時使用的方式,現已漸漸為其他技術取代

為 jQuery 下的 AJAX 操作。$.ajax() 返回其創建的 XMLHttpRequest 對象。

使用範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var list = {}; 
$.ajax({
//請求方式 POST || GET
type : "POST",
//請求的媒體類型
contentType: "application/json;charset=UTF-8",
//請求地址
url : "http://127.0.0.1/xxxx/",
//數據,json字符串
data : JSON.stringify(list),
//請求成功
success : function(result) {
console.log(result);
},
//請求失敗,包含具體的錯誤信息
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
});

缺點為:

  • 須引入JQuery,但JQuery整個專案太大,單純使用ajax卻要引入整個JQuery非常的不合理。
  • 以及容易受到惡意代碼攻擊(CSRF攻擊、XSS攻擊)。什麼是CSRF攻擊及XSS攻擊,請參考ajax、axios、fetch之間優缺點重點對比-CSRF攻擊、XSS攻擊

    Fetch

    Fetch號稱是AJAX的替代品,是在ES6出現的,使用了ES6中的Promise對象。Fetch是基於promise設計的。Fetch的代碼結構比起ajax簡單多了,參數有點像jQuery ajax。但是,一定記住fetch不是ajax的進一步封裝,而是原生js。Fetch函數就是原生js,沒有使用XMLHttpRequest對象。-ajax、axios、fetch之間優缺點重點對比

fetch()是一個全域的方法,包含了需要 fetch 的網址和對應的屬性設定 ( 例如 method、headers、mode、body…等,最基本的寫法屬性不一定要填 ),執行之後會送出 Request,如果得到回應就會回傳帶有 Response 的 Promise 物件,使用 then 將回傳值傳遞下去。
:::warning

使用方式部分注意!還要再補充一些幫助自己了解[color=#ff0000]

基本用法:

1
2
3
4
5
6
fetch('網址')
.then(function(response) {
// 處理 response
}).catch(function(err) {
// 錯誤處理
});

舉例來說,前往 中央氣象局開放資料平台可以取得許多氣象資料,下面的範例使用 局屬氣象站-現在天氣觀測報告,複製 JSON 格式的連結 ( 需要註冊登入才能看得到連結 ),因為檔案為 json 格式,所以在 fetch 取得檔案之後,透過json()的方法處理檔案,接著傳遞到下一層,就能顯示出「高雄市的即時氣溫」。-JavaScript Fetch API 使用教學

1
2
3
4
5
6
7
8
fetch('局屬氣象站-現在天氣觀測報告網址')
.then(res => {
return res.json();
}).then(result => {
let city = result.cwbopendata.location[14].parameter[0].parameterValue;
let temp = result.cwbopendata.location[14].weatherElement[3].elementValue.value;
console.log(`${city}的氣溫為 ${temp} 度 C`); // 得到 高雄市的氣溫為 29.30 度 C
});

Fetch 的 Request 屬性

Fetch 的 Response 屬性

Fetch 的 Response 方法

Fetch 的 Get 用法
Get 是 Fetch 最簡單的方法,使用 Get 必須要將 fetch 第二個參數裡的 method 設定為 get,

1
2
3
4
5
6
7
8
9
10
11
const name = 'oxxo';
const age = 18;
// 有興趣的可以使用下方的網址測試
const uri = `https://script.google.com/macros/s/AKfycbw5PnzwybI_VoZaHz65TpA5DYuLkxIF-HUGjJ6jRTOje0E6bVo/exec?name=${name}&age=${age}`;

fetch(uri, {method:'GET'})
.then(res => {
return res.text(); // 使用 text() 可以得到純文字 String
}).then(result => {
console.log(result); // 得到「你的名字是:oxxo,年紀:18 歲。」
});

Fetch 的 Post 用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const uri = 'https://script.google.com/macros/s/AKfycbxXH6aPsldTBeS41WRMnJEA5Xstc7cYMj6YimDO2Al7H6DkJZiz/exec';
fetch(uri, {
method:'POST',
body:encodeURI(JSON.stringify({
name:'oxxo',
age:18
})),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
})
.then(res => {
return res.json(); // 使用 json() 可以得到 json 物件
}).then(result => {
console.log(result); // 得到 {name: "oxxo", age: 18, text: "你的名字是 oxxo,年紀 18 歲~"}
});

Fetch 搭配 async、await、promise.all

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const postURL = (name,age) => {
const uri = 'https://script.google.com/macros/s/AKfycbxXH6aPsldTBeS41WRMnJEA5Xstc7cYMj6YimDO2Al7H6DkJZiz/exec';
return fetch(uri, {
method:'POST',
body:encodeURI(JSON.stringify({
name:name,
age:age
})),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
})
.then(res => {
return res.json();
}).then(result =>{
console.log(result);
});
};

postURL('oxxo',18);
console.log('hello!!!');
postURL('tom',18);

:::
優點:

  1. 語法簡潔,更加語義化
  2. 基於標準 Promise 實現,支持 async/await
  3. 同構方便,使用 isomorphic-fetch
  4. 更加底層,提供的API豐富(request, response)
  5. 脫離了XHR,是ES規範裡新的實現方式

缺點:

  1. fetchtch只對網路請求報錯,對400,500都當做成功的請求,需要封裝去處理
  2. fetch預設不會帶cookie,需要新增配置項
  3. fetch不支援abort,不支援超時控制,使用setTimeout及Promise.reject的實現的超時控制並不能阻止請求過程繼續在後臺執行,造成了量的浪費
  4. fetch沒有辦法原生監測請求的進度,而XHR可以

Axios

axios不是原生JS的,需要進行安裝,它不但可以在客戶端使用,也可以在nodejs端使用。Axios也可以在請求和響應階段進行攔截。同樣也是基於Promise對象的。特性:從瀏覽器中創建 XMLHttpRequests、從 node.js 創建 http 請求、支持 Promise API、攔截請求和響應等。

執行 GET 請求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 為給定 ID 的 user 創建請求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的請求也可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

執行 POST 請求

1
2
3
4
5
6
7
8
9
10
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})

執行多個併發請求

1
2
3
4
5
6
7
8
9
10
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) {
// 兩個請求現在都執行完成
}));

Axios既提供了併發的封裝,體積也較小,也沒有下文會提到的fetch的各種問題,當之無愧是現在最應該選用的請求的方式。

優缺點:

從 node.js 建立 http 請求
支援 Promise API
客戶端支援防止CSRF
提供了一些併發請求的介面(重要,方便了很多的操作)

參考資料:

只需要知道現在無腦使用axios即可,Jquery老邁笨拙,fetch年輕稚嫩,只有Axios正當其年!