在我們的項目中有用到:
- fetch
有直接用的,也有自己封裝之后用的; - vue-resource
在vue1的時候使用,把方法抽象出來后,總需要往方法里傳 this.$http ,感覺是個超級不爽的設計,在vue2的時候棄用; - Axios
這是一個非常棒的設計,它是借用angularJs的http + httpBackend的概念,對unit test,mocking data比較方便,替換一個假的backend就可以,而且代碼扣除注釋,500行左右;
那么現在我們來詳細了解一下Axios (朋友圈有前端同學叫它 “阿迪奧克斯”😓)
二、詳解axios
1. Axios是什么
Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。(一看是基於promise是不是就對它的API有了大概的了解?哈哈哈)
2. Axios的特點
- 從瀏覽器中創建 XMLHttpRequests
- 從 node.js 創建 http 請求
- 支持 Promise API
- 攔截請求和響應 (就是有interceptor)
- 轉換請求數據和響應數據
- 取消請求
- 自動轉換 JSON 數據
- 客戶端支持防御 XSRF
ps: 可能大家對interceptor(攔截器)並不是很熟悉,在這里作下介紹,攔截器可以在請求發送前和發送請求后做一些處理。有一張圖可以清晰的了解它在一次HTTP請求中做了什么,如下圖

image.png
3.兼容性

image.png
4.安裝
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
5.基本用法
//執行get請求 // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }).catch(function (error) { console.log(error); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); });
是不是都在then,catch里處理response,感覺fetch差不多,寫起來很方便
6.使用流程
本來想在這貼Axios API,這跟大家讀api文檔無異,所以在這里貼一下我們是如何使用的吧,或許對你更有幫助
//首先我們來創建一個Axios實例 var axiosIns = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-product': 'h5'} }); //設置request攔截器 axiosIns.interceptors.request.use((request) => { //在這里處理request,可以對所有請求統一處理請求頭等 }) //設置response攔截器 axiosIns.interceptors.response.use((response) => { //在這里處理response,這是全局的,對所有使用axios的請求起作用 });
//可以將上邊的創建實例和設置的攔截器封裝成函數,之后直接調用就Ok //實例方法 //以下是可用的實例方法。指定的配置將與實例的配置合並 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]]) //請求配置 { // `url` 是用於請求的服務器 URL url: '/user', // `method` 是創建請求時使用的方法 method: 'get', // 默認是 get // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它可以通過設置一個 `baseURL` 便於為 axios 實例的方法傳遞相對 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允許在向服務器發送前,修改請求數據 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 // 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數據 transformResponse: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `headers` 是即將被發送的自定義請求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即將與請求一起發送的 URL 參數 // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 params: { ID: 12345 }, // `paramsSerializer` 是一個負責 `params` 序列化的函數 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` 是作為請求主體被發送的數據 // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設置 `transformRequest` 時,必須是以下類型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: 'Fred' }, // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) // 如果請求話費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否需要使用憑證 withCredentials: false, // 默認的 // `adapter` 允許自定義處理請求,以使測試更輕松 // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 // 這將設置一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設置的自定義 `Authorization`頭 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默認的 // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的 // `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `maxContentLength` 定義允許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // 默認的 }, // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 // 如果設置為0,將不會 follow 任何重定向 maxRedirects: 5, // 默認的 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項: // `keepAlive` 默認沒有啟用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定義代理服務器的主機名稱和端口 // `auth` 表示 HTTP 基礎驗證應當用於連接代理,並提供憑據 // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `Proxy-Authorization` 頭。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用於取消請求的 cancel token // (查看后面的 Cancellation 這節了解更多) cancelToken: new CancelToken(function (cancel) { }) }
補充說明:
XMLHttpRequest 或 Fetch都是瀏覽器實現的功能,而axios是我們封裝的axios庫
作者:瓦斯程序媛
鏈接:https://www.jianshu.com/p/065294e2711c