1. 程式人生 > >二次封裝axios請求(React、Vue皆可使用)

二次封裝axios請求(React、Vue皆可使用)

日結部落格 04.19.18 HZ

對於每次都要從頁面匯入axios和配置路徑的行為簡直沒完沒了地厭惡,每次後臺修改api地址都得從一大堆頁面裡尋找到那小小的一個axios.get,簡直深惡痛絕

請封裝吧,萬物皆能封裝,封裝治好了你多年的眼疾

封裝更合理的Axios操作類

1.匯入axios至你的專案

npm install --save axios

2.在根路徑建立http.js

首先匯入axios至http檔案


import axios from 'axios'import axios from 'axios'

配置axios的預設URL

axios.defauls.baseURL = 'xxx'

配置允許跨域攜帶cookie

axios.defaults.withCredentials = true

配置超時時間

axios.defaults.timeout = 100000

標識這是一個 ajax 請求


axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'

配置請求攔截

 axios.interceptors.request.use(config => {
    config.setHeaders([
        ...
        // 在這裡設定請求頭與攜帶token資訊
    ])
    return config
 })
  config.setHeaders([       ...       // 在這裡設定請求頭與攜帶token資訊   ]) return config })

配置相應攔截

// axios攔截器
axios.interceptors.response.use(response => {
 // 在這裡你可以判斷後臺返回資料攜帶的請求碼
if (response.data.retcode === 200 || response.data.retcode === '200') {
  return response.data.data || response.data
}else {
  // 非200請求抱錯
  throw Error(response.data.msg || '服務異常')
}
​
axios.interceptors.response.use(response => { // 在這裡你可以判斷後臺返回資料攜帶的請求碼 if (response.data.retcode === 200 || response.data.retcode === '200') { return response.data.data || response.data }else { // 非200請求抱錯 throw Error(response.data.msg || '服務異常') } ​

最後返回(更多配置可以檢視axio的官方api)


export defaul axiosexport defaul axios

全部檔案

import axios from 'axios'
axios.defauls.baseURL = 'xxx'
axios.defaults.withCredentials = true
axios.defaults.timeout = 100000
// // axios攔截器
 axios.interceptors.request.use(config => {
    config.setHeaders([
        ...
        // 在這裡設定請求頭與攜帶token資訊
    ])
    return config
 })
 
 axios.interceptors.response.use(response => {
     // 在這裡你可以判斷後臺返回資料攜帶的請求碼
    if (response.data.retcode === 200 || response.data.retcode === '200') {
      return response.data.data || response.data
    }else {
      // 非200請求抱錯
      throw Error(response.data.msg || '服務異常')
 }
​
export default axios
axios.defauls.baseURL = 'xxx'
axios.defaults.withCredentials = true
axios.defaults.timeout = 100000
// // axios攔截器
 axios.interceptors.request.use(config => {
    config.setHeaders([
        ...
        // 在這裡設定請求頭與攜帶token資訊
    ])
    return config
 })
 
 axios.interceptors.response.use(response => {
     // 在這裡你可以判斷後臺返回資料攜帶的請求碼
    if (response.data.retcode === 200 || response.data.retcode === '200') {
      return response.data.data || response.data
    }else {
      // 非200請求抱錯
      throw Error(response.data.msg || '服務異常')
 }
​
export default axios

是不是看到這裡大失所望,彆著急,接下來再新建一個api.js檔案

封裝一個匿名函式返回一個apis物件,通過apis物件的鍵名去獲取對應的api地址

// 集中管理路由,所有的介面地址:
//  1.整個應用用到了哪些介面一目瞭然
//  2.介面地址可能變化,方便管理
​
const prefix = '' // api地址字首
export default(config => {
    return Object.keys(config).reduce((copy, name) => {
      copy[name] = `${prefix}$config[name]`
      return copy
    }, {})
})({
  // example api
  "getExampleData": "/api/example/data" 
})
​
//  1.整個應用用到了哪些介面一目瞭然
//  2.介面地址可能變化,方便管理
​
const prefix = '' // api地址字首
export default(config => {
    return Object.keys(config).reduce((copy, name) => {
      copy[name] = `${prefix}$config[name]`
      return copy
    }, {})
})({
  // example api
  "getExampleData": "/api/example/data" 
})
​

檔案最終返回一個物件

// api物件
{
  getExampleData: '/api/example/data'
}
{
  getExampleData: '/api/example/data'
}

看到這裡是不是有點迷糊,接下來上重頭戲~

再新建一個service資料夾,在其下新建一個index.js

(src/server/index.js)


import http from '../http.js' // 匯入我們封裝好的axios物件
import apis from '../api.js' // 匯入我們封裝好的apis物件
​
export funciton getExampleData (params = {}) { // 從外部接受引數,沒有引數預設為空物件
    retun http.get(apis.getExampleData, params) // return對應的get/post方法,第一個填路徑,第二個給引數物件
}import http from '../http.js' // 匯入我們封裝好的axios物件
import apis from '../api.js' // 匯入我們封裝好的apis物件
​
export funciton getExampleData (params = {}) { // 從外部接受引數,沒有引數預設為空物件
    retun http.get(apis.getExampleData, params) // return對應的get/post方法,第一個填路徑,第二個給引數物件
}

看到這裡是不是就恍然大悟了,把獲取exampleData這個介面封裝成了一個方法,在所需的頁面呼叫對應的方法就好了

Vue頁面引用

import { getExampleData } from 'services'
​
...
beforeCreate() {
    getExampleData({ name: 'xxx'} ).then(res => {
        this.exampleData = res // 繫結到data裡
        consonle.log(res) // 這裡返回的是你根據http.js攔截器中定義的返回資料
    }).catch(err => console.log(err)) // 處理報錯資訊
}
...
​
...
beforeCreate() {
    getExampleData({ name: 'xxx'} ).then(res => {
        this.exampleData = res // 繫結到data裡
        consonle.log(res) // 這裡返回的是你根據http.js攔截器中定義的返回資料
    }).catch(err => console.log(err)) // 處理報錯資訊
}
...

React頁面引用

import { getExampleData } from 'services'
​
...
componentWillMount() {
    getExampleData({ name: 'xxx'} ).then(res => {
        this.setState({
            exampleData: res // 賦值到state裡
        })
        consonle.log(res) // 這裡返回的是你根據http.js攔截器中定義的返回資料
    }).catch(err => console.log(err)) // 處理報錯資訊
}
​
...
componentWillMount() {
    getExampleData({ name: 'xxx'} ).then(res => {
        this.setState({
            exampleData: res // 賦值到state裡
        })
        consonle.log(res) // 這裡返回的是你根據http.js攔截器中定義的返回資料
    }).catch(err => console.log(err)) // 處理報錯資訊
}

希望大家能用上這個以後不再煩惱apis的雜多或者難以管理,難以修改之類的通病

喜歡就點個贊吧。謝謝你~

:D