Fetch API 與 Axios
ES6的出現帶來了Promise語法,實現了js的callback的變化;XHR是ajax請求的基礎,以往的非同步請求用到了大量的ajax譬如jq等,Promise的基礎上封裝的Fetch API更加優雅 已經大量用於客服端和伺服器端,譬如 Axios,本文主要講述Fetch API 與 Ajax的不同點和基礎應用,和Axios API
XHR 與 Fetch 傳送請求
使用XHR傳送請求:
var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'json'; xhr.onload = function() { console.log(xhr.response); }; xhr.onerror = function() { console.log("Oops, error"); }; xhr.send(); 複製程式碼
- 建立XML
- 傳送請求
- 通過回撥獲取響應資訊
使用 Fecth API 傳送請求如下:
fetch(url).then( response => response.json() ).then( data => console.log(data) ).catch( e => console.log("Oops, error", e) ) 複製程式碼
這種是鏈式寫法,第一個獲取請求成功資訊,第二個獲取請求失敗資訊,第三個捕獲異常
Fetch 與 XHR 不同
- Fetch接收到錯誤狀態碼『404, 500 ...』時候, 返回的Promise狀態為 resolve『完成狀態』,只有在網路故障或者請求被阻止『跨域』才是reject『拒絕狀態』。而XHR 會直接返回為error
- Fetch需要設定credentials才能從服務端傳送或接收任何 cookies
Fetch API 基本應用
fetch 接受兩個引數,一個是URL,另一個「可選」是請求體「method,body,headers...」
- 傳送GET請求:
fetch('https://example.com') 複製程式碼
- 傳送 POST請求:
var url = 'https://example.com/profile'; var data = {username: 'example'}; fetch(url, { method: 'POST', // or 'PUT' body: JSON.stringify(data), // data can be `string` or {object}! headers: new Headers({ 'Content-Type': 'application/json' }) 複製程式碼
其他參照MDN文件
基於Promise封裝的js庫「axios API」
用法是Fetch與JQ的大集合
- GET請求
axios.get('https://example.com') 複製程式碼
- URL帶參請求:
axios.get('/user?ID=12345') // 用 params 封裝 axios.get('/user', { params: { ID: 12345 } }) 複製程式碼
- POST請求:
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) 複製程式碼
- 傳遞配置建立請求:
axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); 複製程式碼
- 同時內建了其他方法
axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) 複製程式碼