[关闭]
@zhouyy 2018-05-27T16:34:40.000000Z 字数 3064 阅读 503

axios封装

vue


来源:https://zhuanlan.zhihu.com/p/33651927

  1. import Vue from 'vue'
  2. import { ToastPlugin, md5 } from 'vux'
  3. import axios from 'axios'
  4. import store from './store' // 从 vuex 里取出一些有用的信息
  5. Vue.use(ToastPlugin)
  6. // 前根据 location.host 判断测试 or 正式环境
  7. const devUrl = '/dev'
  8. const prodUrl = 'https://zhuanlan.zhihu.com'
  9. const testUrl = 'https://test/api'
  10. const isTest = loaction.host === 'https://test/api' ? 1 : 0
  11. const baseUrl = process.env.NODE_ENV === 'production' ? (isTest ? testUrl : prodUrl) : devUrl
  12. // 建议不要直接调用axios,采用创建实例的方式
  13. // 集中处理异常情况
  14. const instance = axios.create({
  15. timeout: 15000 // 请求超时时间
  16. })
  17. const method = (type, api, params) => {
  18. return new Promise((resolve, reject) => {
  19. instance[type](api, params).then(data => {
  20. if (data.status === 200 && data.data.status === 200) {
  21. resolve(data.data)
  22. } else {
  23. Vue.$vux.toast.show({
  24. type: 'warn',
  25. time: 1500,
  26. text: data.data.msg
  27. })
  28. }
  29. }).catch((err) => {
  30. Vue.$vux.toast.show({
  31. type: 'warn',
  32. time: 1500,
  33. text: '服务器繁忙'
  34. })
  35. reject(err)
  36. })
  37. })
  38. }
  39. /**
  40. * 加密算法
  41. * @params {*} 和后台商量要的参数
  42. */
  43. const generateSignature = (param1, param2, param3) => md5()
  44. /**
  45. * 拼接api默认参数
  46. * @param {*} api: 接口相对路径
  47. */
  48. const stitching = (api) => {
  49. const val1 = store.getters.key1
  50. const val2 = store.getters.key2
  51. const val3 = 'value1'
  52. const timeStamp = Date.parse(new Date()) / 1000
  53. const sign = generateSignature(val1, val2, val3)
  54. return `${api}?timeStamp=${timeStamp}&key1=${val1}&key2=${val2}&key3=${val3}&sign=${sign}`
  55. }
  56. /**
  57. * post请求时携带的默认参数
  58. */
  59. const extend = (data) => {
  60. return Object.assign({
  61. userId: store.getters.userInfo.userId
  62. }, data)
  63. }
  64. const ajaxGet = (api, data = null) => {
  65. return method('get', baseUrl + stitching(api), {params: data})
  66. }
  67. const ajaxPost = (api, data = null) => {
  68. return method('post', baseUrl + stitching(api), extend(data))
  69. }
  70. export {
  71. ajaxGet,
  72. ajaxPost
  73. }

这是对 axios 做封装的一种形式,其中 generateSignature 函数是用来生成签名,通常需要携带时间戳,进行实效性验证。stitching 函数是用来对接口进行拼接处理的,post 和 get 请求的某些参数后台都会这里面拿。 extend 是为了 post 请求准备的。
当然还有了另一种形式的封装:

  1. import axios from 'axios'
  2. import { stringify } from 'qs'
  3. import Cookies from 'js-cookie'
  4. import { Toast } from 'vant'
  5. const devUrl = '/liangchaowei'
  6. const prodUrl = 'https://zhihu.com/api/'
  7. const baseUrl = process.env.NODE_ENV === 'production' ? prodUrl : devUrl
  8. const userInfo = JSON.parse(localStorage.getItem('userInfo') || Cookies.get('userInfo'))
  9. /**
  10. * 设置请求头
  11. */
  12. const getToken = data => {
  13. const { value1, value2 } = userInfo
  14. const secretKey1 = value1 || 'default'
  15. const secretKey2 = value2 || 'default'
  16. const newData = {}
  17. for (const key in data) {
  18. // 对象请求参数一系列操作
  19. }
  20. return {
  21. 'X-customize-header1': secretKey1,
  22. 'X-customize-header2': secretKey2
  23. }
  24. }
  25. const instance = axios.create({
  26. timeout: 10000
  27. })
  28. const method = (type, api, params, options) => {
  29. return new Promise((resolve, reject) => {
  30. instance[type](api, params, options).then(data => {
  31. if (data.status === 200 && data.data.code === 1) {
  32. resolve(data.data)
  33. } else {
  34. Toast({
  35. type: 'fail',
  36. message: data.data.msg,
  37. duration: 1000
  38. })
  39. }
  40. }).catch((err) => {
  41. reject(err)
  42. })
  43. })
  44. }
  45. const extend = (data, body) => {
  46. return Object.assign(body, data)
  47. }
  48. const ajaxGet = (api, data = null) => {
  49. const time = new Date().getTime()
  50. let body = {
  51. time: time,
  52. sign: getSign(time),
  53. userId: userInfo.userId
  54. }
  55. return method('get', baseUrl + api, {params: extend(data, body), headers: getToken(extend(data, body))})
  56. }
  57. const ajaxPost = (api, data = null) => {
  58. const time = new Date().getTime()
  59. let body = {
  60. time: time,
  61. sign: getSign(time),
  62. userId: userInfo.userId
  63. }
  64. return method('post', baseUrl + api, stringify(extend(data, body)), {headers: getToken(extend(data, body))})
  65. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注