封装网络请求工具及文件上传示例
图
开发uni-app的项目时,提供了uni.request来请求网络,但是很是有很多功能需要封装才能使用,不然单独使用很麻烦,比如统一定义接口地址,拦截器的处理等

个人封装示例

该方式主要是解决统一请求地址、函数中不干扰this问题

import Vue from 'vue'
let api = Vue.prototype.baseUrl


let user = uni.getStorageSync('userData')
let uid = ''
if(user) {
  uid = user.userId
}

export default function request(url, method = 'GET', params = {}, successFun, failFun) {
  url = api + url
  uni.request({
    url,
    data: params,
    method,
    header: {
      uid: uid
    },
    success(res) {
      console.log(res);
      successFun(res.data)
    },
    fail(err) {
      failFun(err)
    }
  })
}

接口地址放在了main.js中

// Vue.prototype.baseUrl = 'https://fanmr.cn/handiness'
Vue.prototype.baseUrl = 'http://192.168.100.8:18090'

使用方式

import httpUtil from "../../common/httpUtil.js"

httpUtil('/app/update/last', 'POST', {}, (res) => {
  console.log('成功', res);
}, (err) => {
  console.log('失败', err);
  this.$refs.uToast.show({message:'请求失败'})
})

文件上传(form-data)

// 获取头像
onChooseAvatar(e) {
  // 上传头像到服务器
  const tempFilePath = e.detail.avatarUrl;
  let that = this
  wx.uploadFile({
    url: that.baseUrl + '/uploadFile',
    filePath: tempFilePath,
    name: 'file',
    header: {
      'content-type': 'multipart/form-data',
    },
    success(res) {
      let resData = JSON.parse(res.data)
      console.log(resData);
      that.info.avatar = resData.data
      that.avatarUrl = that.baseUrl + that.info.avatar
    },
    fail(error) {
      console.log('upload failed', error);
    }
  });