沐鳴總代理_axios的使用

什麼是 axios?

Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。支持從瀏覽器中創建XML請求,支持 node.js中發出http請求,支持攔截請求和響應,支持轉換請求和響應數據,支持自動轉換JSON數據,客戶端支持防禦 XSRF。

axios安裝

使用 npm:

npm install axios

使用 bower:

bower install axios

使用 cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axios基本使用

執行 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的封裝

封裝目的:避免重複設置超時時間,請求頭,錯誤處理;提高代碼質量。

config.js文件

// axios中請求配置有baseURL選項,表示請求URL公共部分。
// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL

export const baseURL = 'http://XXXXXXXX.com/'

axios.js文件

import axios from 'axios'
import qs from 'qs'
// 在config.js文件中統一存放一些公共常量,方便之後維護
import { baseURL } from './config.js'

// 添加請求攔截器,在發送請求之前做些什麼(**具體查看axios文檔**)
axios.interceptors.request.use(function (config) {
// 显示loading
return config
}, function (error) {
// 請求錯誤時彈框提示,或做些其他事
return Promise.reject(error)
})

// 添加響應攔截器(**具體查看axios文檔**)
axios.interceptors.response.use(function (response) {
// 對響應數據做點什麼,允許在數據返回客戶端前,修改響應的數據
// 如果只需要返回體中數據,則如下,如果需要全部,則 return response 即可
return response.data
}, function (error) {
// 對響應錯誤做點什麼
return Promise.reject(error)
})

// 封裝數據返回失敗提示函數---------------------------------------------------------------------------
function errorState (response) {
// 隱藏loading
// 如果http狀態碼正常,則直接返回數據
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
// 如果不需要除了data之外的數據,可以直接 return response.data
return response
} else {
alert('數據獲取錯誤')
}
}

// 封裝數據返回成功提示函數
function successState (res) {
// 隱藏loading
// 統一判斷後端返回的錯誤碼(錯誤碼與後台協商而定)
if (res.data.code === '000000') {
alert('success')
return res
}
}

// 封裝axios
function apiAxios (method, url, params) {
let httpDefault = {
method: method,
baseURL: baseURL,
url: url,
// `params` 是即將與請求一起發送的 URL 參數
// `data` 是作為請求主體被發送的數據
params: method === 'GET' || method === 'DELETE' ? params : null,
data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
timeout: 10000
}

// 注意**Promise**使用(Promise首字母大寫)
return new Promise((resolve, reject) => {
axios(httpDefault)
// 此處的.then屬於axios
.then((res) => {
successState(res)
resolve(res)
}).catch((response) => {
errorState(response)
reject(response)
})
})
}
export default apiAxios

站長推薦

1.雲服務推薦: 國內主流雲服務商,各類雲產品的最新活動,優惠券領取。地址:阿里雲騰訊雲華為雲

鏈接: http://www.fly63.com/article/detial/10230