vue中axios請求的封裝

1.發送請求模塊目錄

clipboard.png

2.@/api/url中存放的是每一個模塊的URL

// 商品模塊 product.js
const product = {
  sku: {
    list: '/product/product/speclist',
    options: '/product/product/options'
  }
}
export default product

// 公用請求模塊 common.js
const common = {
  region: {
    provinces: '/region/region/list',
    cities: '/region/region/list'
  },
  upload: {
    image: '/product/product/upload'
  }
}
export default common

發送請求的時候只須要指定key(sku/list),如:this.$ajax('sku/list', param);假定axios設置的baseURL是http://prod.storm.com/api/,那麼最終的請求地址:http://prod.storm.com/api/product/product/speclistwebpack

3.requireURLs.js

使用webpack提供的require.context將src/api/url下後綴爲js的全部文件引入,並整理出一個對象。ios

let urls = {}
const req = require.context('./url', false, /\.js$/)

const requireAll = requireContext => requireContext.keys().map(i => {
  let url = requireContext(i)
  Object.assign(urls, url.default)
})
requireAll(req)
export default urls

整合common.js & product.js,最終獲得的對象以下:web

urls = {
  sku: {
    list: '/product/product/speclist',
    options: '/product/product/options'
  },
  region: {
    provinces: '/region/region/list',
    cities: '/region/region/list'
  },
  upload: {
    image: '/product/product/upload'
  }
}
// 注意:模塊名product和common沒有了,因此須要注意命名的惟一,以避免覆蓋。

4.ajax.js

import axios from 'axios'
import qs from 'qs'
import jsd from 'js-file-download'
import store from '@/store'
import urlObj from './requireURLs'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: `${process.env.BASE_API}/api/`, // 不一樣環境(dev/prod/test)使用不一樣的baseURL
  timeout: 5000
})
service.interceptors.request.use(
  config => {
    // 上傳文件時,config.data的數據類型是FormData,
    // qs.stringify(FormData)的結果是空字符串,致使接口報**參數爲空**的錯誤
    if (config.method === 'post' && config.data.constructor !== FormData) {
      config.data = qs.stringify(config.data)
    }
    if (store.getters.token) {
      config.headers.common['Auth-Token'] = getToken()
      // Auth-Token 登陸過時後,從新登陸不傳token
      if (!config.headers.common['Auth-Token']) {
        delete config.headers.common['Auth-Token']
      }
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    const res = response.data // 後臺會把{ code, data, msg }返回到response.data中
    if (response.headers['content-type'].indexOf('application/vnd.ms-excel') !== -1) {
      // 經過請求接口下載Excel,因爲後臺返回的數據中(res)沒有code(我也不知道爲何,反正後臺就說沒有),因此我只好經過響應頭的content-type判斷了
      // 下載接口返回的response header以下(後臺把文件名放在Content-Disposition中(filename))
      // Content-Disposition: attachment; filename=20190323211209.csv
      // Content-Type: application/vnd.ms-excel;charset=GBK
      let fileName = response.headers['content-disposition'].split('=')[1]
      jsd(res, fileName)
      return
    }
    if (res.code === 0) { // 和後臺約定code:0表明請求成功
      return res
    } else {
      if (res.code === 18500) { // 和後臺約定code:18500表明token未過時,可是被更新了
        handleLogin('您已被登出,請從新登陸')
      } else if (res.code === 18501) { // 和後臺約定code:18500表明token過時
        handleLogin('登陸已失效,請從新登陸')
      } else {
        // 統一處理接口的報錯信息,若是須要具體到頁面去處理,能夠和後臺另外約定一個code
        Message({
          message: res.msg,
          type: 'error',
          duration: 3 * 1000
        })
      }
      return Promise.reject(res)
    }
  },
  error => {
    let data = error.response.data
    Message({
      message: data.msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(data)
  }
)

const handleLogin = title => {
  MessageBox.confirm(title, '提示', {
    confirmButtonText: '從新登陸',
    showCancelButton: false,
    showClose: false,
    type: 'warning'
  }).then(() => {
    store.dispatch('FedLogout').then(() => {
      location.reload()
    })
  })
}

const ajax = (path, data = {}, options = {}) => {
  // 若是path以http開頭指定了一個url,直接用;不然就去遍歷步驟3中的urls對象。以下:
  // this.$ajax('http://test.storm.com'),url = 'http://test.storm.com'
  // this.$ajax('sku/list'),url = '/product/product/speclist'
  let url = path.indexOf('http') === -1 ? path.split('/').reduce((o, k) => {
    return o[k]
  }, urlObj) : path
  let method = options.method || 'post'
  let params = { url, method }
  
  // 因爲我司後臺提供的接口大都是post和get,因此只考慮了這兩種請求方式
  if (options.method === 'get') {
    Object.assign(params, { params: data }, options)
  } else {
    // post
    Object.assign(params, { data }, options)
  }
  return service(params)
}

export default ajax

5.在src/plugins中建立一個ajaxPlugin.js,並在src/main.js中引用

// ajaxPlugin.js
import ajax from '@/api/ajax'

let ajaxPlugin = {}

ajaxPlugin.install = Vue => {
  Vue.prototype.$ajax = ajax
}

export default ajaxPlugin

// main.js
import ajaxPlugin from '@/plugins/ajaxPlugin'

Vue.use(ajaxPlugin)

6.發送請求:

this.$ajax('sku/list').then(res => {})
相關文章
相關標籤/搜索