Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
axios的作用是什么呢?
axios主要是用於向后台發起請求的,還有在請求中做更多是可控功能。
axios 特點:
- 從瀏覽器中創建 XMLHttpRequests
- 從 node.js 創建 http 請求
- 支持 Promise API
- 攔截請求和響應 (就是有interceptor)
- 轉換請求數據和響應數據
- 取消請求
- 自動轉換 JSON 數據
- 客戶端支持防御 XSRF
簡單介紹一下promise 吧。 (ps:高手寫代碼用的都是面向對象,所以根本不用這個回調地獄的手法,promise 主要是用來解決異步問題的,由於很多程序員都是同步思考習慣了,異步思起來就挺麻煩,所以代碼會出現一套嵌套這一套,當多起來的時候那真的是可以寫出一條長龍。先說一個簡單應用把,比如圖片的預加載,這可以用promise來寫,因為圖片大小不同,如果一下子全部加載,會出現堵住,第一張圖片加載完了之后開始第二張圖片加載,promise就是干這個事情的,“你好了沒有?好了就到我了”)
promise是什么:是一個對象用來傳遞異步操作的信息,它代表了某個未來才會知道結果的事件(通常是一個異步操作),並且這個事件提供統一的api,可供進一步的處理。
promise的作用:Promise的出現主要是解決地獄回調的問題,比如你需要結果需要請求很多個接口,這些接口的參數需要另外那個的接口返回的數據作為依賴,這樣就需要我們一層嵌套一層,但是有了Promise 我們就無需嵌套。
promise的本質是什么:分離異步數據獲取和業務
ps: 可能大家對interceptor(攔截器)並不是很熟悉,在這里作下介紹,攔截器可以在請求發送前和發送請求后做一些處理。有一張圖可以清晰的了解它在一次HTTP請求中做了什么,如下圖

攔截器
在請求或響應被 then 或 catch 處理前攔截它們(攔截器可以做什么:在請求或者響應時攔截下來進行處理)
攔截器分為請求攔截器和響應攔截器
請求攔截器(interceptors.requst)是指可以攔截每次或指定HTTP請求,並可修改配置項。
響應攔截器(interceptors.response)可以在每次HTTP請求后攔截住每次或指定HTTP請求,並可修改返回結果項。

執行get請求
// 為給定 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請求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
執行多個並發請求
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傳遞相關的配置來創建請求
axios(config)
// 發送 POST 請求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
axios(url[,config])
// 發送 GET 請求(默認的方法) axios('/user/12345');
axios提供了一下幾種請求方式
1.axios.get(url[, config]) 執行 GET 請求 eg: // 向具有指定ID的用戶發出請求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 也可以通過 params 對象傳遞參數 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 2.axios.post(url[, data[, config]]) 執行 POST 請求 eg: axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); 3.axios.request(config) 4.axios.head(url[, config]) 5.axios.delete(url[, config]) 6.axios.put(url[, data[, config]]) 7.axios.patch(url[, data[, config]]) 8.axios.all(iterable)執行多個並發請求 eg: 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) { // 兩個請求現在都執行完成 })); 9.axios.spread(callback) 注意:處理並發請求的助手函數axios.all(iterable) axios.spread(callback)
請求配置
這些是創建請求時可以用的配置選項。只有 url 是必需的。如果沒有指定 method,請求將默認使用 get 方法。
//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) { }) }
響應結構
某個請求的響應包含以下信息
{ // `data` 由服務器提供的響應 data: {}, // `status` 來自服務器響應的 HTTP 狀態碼 status: 200, // `statusText` 來自服務器響應的 HTTP 狀態信息 statusText: 'OK', // `headers` 服務器響應的頭 headers: {}, // `config` 是為請求提供的配置信息 config: {} }
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) {
// 兩個請求現在都執行完成
}));