uni.request() 二次封装

uni.request() 二次封装

import Vue from 'vue'

const baseUrl = 'http://127.0.0.1:8080' // 服务器地址
const imageUrl = baseUrl

const staticVariables = {
  BASE_URL: baseUrl + '/api',
  TIME_OUT: 10000,
  SSL_VERIFY: false,
  DURATION: 500,
  MASK: true,
  TOKEN_PREFIX: 'Bearer ',
  FORM_DATA: 'application/x-www-form-urlencoded',
  JSON: 'application/json'
}

/**
 * 上传图片到本地服务器
 * @param path
 * @param baseOrFile
 * @param fileType 可选值:base64/file
 * @param type  可选值:image/video/audio
 * @returns fileName
 */
const uploadFileToServe = (path, baseOrFile, fileType = 'file', type = 'image') => {
  let file = void 0
  if (fileType === 'base64') {
    const base64 = {
      dataURL: baseOrFile, // 用url方式表示的base64图片数据
      type: 'image/png' // 文件类型
    }
    const result = convertBase64UrlToBlob(base64)
    file = blobToFile(result, (new Date().getTime() + '.png'))
  } else {
    file = baseOrFile
  }
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: staticVariables.BASE_URL + path,
      header: {
        'Authorization': Vue.prototype.TOKEN_PREFIX + uni.getStorageSync('token')
      },
      file: file,
      fileType: "image",
      name: "file",
      success: (res) => {
        const object = JSON.parse(res.data);
        console.log(object);
        if (object.code === 0) {
          resolve(object.data.fileName)
        } else {
          if (object.code === 422) {
            console.log(Vue.prototype.$store);
            Vue.prototype.$store.commit('logout')
            uni.reLaunch({
                url: '/pages/login/login'
              })
          } else {
            console.log("失败原因" + object);
            uni.showToast({
              title: object.msg,
              icon: "error",
              duration: 1000
            })
            reject(object.msg)
          }

        }
      },
      fail: (err) => {
        reject(err)
        throw new Error(err);
      }
    })
  })
}

/**
 * base64转blob
 * @param base64
 * @returns {Blob}
 */
const convertBase64UrlToBlob = (base64) => {
  let urlData = base64.dataURL
  let type = base64.type
  let bytes = null
  if (urlData.split(',').length > 1) {//是否带前缀
    bytes = window.atob(urlData.split(',')[1]) // 去掉url的头,并转换为byte
  } else {
    bytes = window.atob(urlData)
  }
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length)
  let ia = new Uint8Array(ab)
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], { type: type })
}

/**
 * 将blob转换为file
 * @param theBlob
 * @param fileName
 * @returns {*}
 */
const blobToFile = (theBlob, fileName) => {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}

/**
 * object转换为formData格式
 * @param data
 * @returns {string}
 */
const qs = (data) => {
  let ret = ''
  for (let it in data) {
    ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
  }
  return ret.substring(0, ret.length - 1)
}

/**
 * 请求工具
 * @param url
 * @param method
 * @param ContentType
 * @param data
 * @param isLoading
 * @returns {Promise<unknown>}
 */
const request = (url, method, ContentType, data, isLoading = true) => {
  if (isLoading) {
    uni.showLoading({
      title: "请求中...",
      mask: staticVariables.MASK
    })
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: staticVariables.BASE_URL + url,
      method: method,
      data: data,
      header: {
        'Content-Type': ContentType,
        'Authorization': uni.getStorageSync('token')
      },
      timeout: staticVariables.TIME_OUT,
      sslVerify: staticVariables.SSL_VERIFY,
      success(res) {
        if (res.data.code === 0) {
          resolve(res.data)
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none'
          });
          reject(res.data)
        }

      },
      fail(err) {
        uni.showToast({
          title: err.errMsg,
          icon: 'none'
        });
        reject(err)
      },
      complete() {
        setTimeout(() => {
          uni.hideLoading()
        }, 200)
      },
    });
  })
}

const get = async(url, data, isLoading) => {
  return await request(url, 'get', staticVariables.JSON, data, isLoading)
}

const getForm = async(url, data, isLoading) => {
  return await request(url, 'get', staticVariables.FORM_DATA, data, isLoading)
}

const post = async(url, data, isLoading) => {
  return await request(url, 'post', staticVariables.JSON, data, isLoading)
}

const postForm = async(url, data, isLoading) => {
  return await request(url, 'post', staticVariables.FORM_DATA, qs(data), isLoading)
}

const put = async(url, data, isLoading) => {
  return await request(url, 'put', staticVariables.JSON, data, isLoading)
}

const putForm = async(url, data, isLoading) => {
  return await request(url, 'put', staticVariables.FORM_DATA, qs(data), isLoading)
}

const deleted = async(url, data, isLoading) => {
  return await request(url, 'delete', staticVariables.JSON, data, isLoading)
}

const deletedForm = async(url, data, isLoading) => {
  return await request(url, 'delete', staticVariables.FORM_DATA, qs(data), isLoading)
}

Vue.prototype.uploadFileToServe = uploadFileToServe
Vue.prototype.get = get
Vue.prototype.getForm = getForm
Vue.prototype.post = post
Vue.prototype.postForm = postForm
Vue.prototype.put = put
Vue.prototype.putForm = putForm
Vue.prototype.deleted = deleted
Vue.prototype.deletedForm = deletedForm
Vue.prototype.imageUrl = imageUrl

export default {
  uploadFileToServe, get, getForm, post, postForm, put, putForm, deleted, deletedForm, imageUrl
}

使用的话只需在main.js导入即可使用

// main.js
import '@/common/request.js'

// 使用
this.get('/test/test')
this.post('/test/test', {data: '1'})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值