uniapp请求封装

这里就简单记录一下吧,也做了挺长时间uniapp了,希望下次换个项目做的时候,能直接从这里拷过去用

大家都知道再uniapp中给我们提供的uni.request()来供我们发请求使用,它里面有 success、fail、complete三个回调函数,如果每次发请求都去写uni.request那整个项目下来真是超级繁琐,而且不好维护、也不好统一,且代码可读性不强。所以这里我们采用Promise进行二次封装,直接调用方法传入接口地址、参数等即可,不说废话了,下面直接上代码:

我这里在项目根目录下新建了common文件夹,里面新建了request.js 

也就是@/common/request.js 

import BASE_URL from './config.js'
import qs from 'qs'

export default function request(body) {
  let { url, method, data, header, params, responseType } = body
  data = data || params || {};
  header = header || { 'Content-Type': 'application/json; charset=utf-8' }
  method = method.toUpperCase() || "GET";
  responseType = responseType || "text"
  let token = uni.getStorageSync('token')
  if (token) {
    header.token = token;			// 获取token值
  }
  if ((method === 'POST' || method === 'PUT') && header['Content-Type'] === 'application/x-www-form-urlencoded; charset=utf-8') {
    data = qs.stringify(data, { allowDots: true, arrayFormat: 'indices' })
  } else if (method === 'GET' || method === 'DELETE') {
    url = url + '?' + qs.stringify(data, { allowDots: true, arrayFormat: 'indices' })
    data = null
  }
  let promise = new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      header: header,
      data: data,
      method: method,
      responseType: responseType,
      success: res => {
        if (res && res.statusCode !== 200) {
          error(res);
          reject(res)
        }
        resolve(res);
      },
      fail: res => {
        uni.hideLoading();
        error(res);
        reject(res);
      },
      complete: () => {}
    })
  })
  return promise;
}

// 单文件上传
export function upload(url, filePath, filename, formData, header) {
  let name = filename || 'file';
  header = header || {};
  let token = uni.getStorageSync('token')
  if (token) { // 获取token值
    header.token = token;
  }
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + url,
      filePath: filePath,
      name: name,
      formData: formData || {},
      header: header,
      success: res => {
        resolve(res.data);
      },
      fail: (res) => {
        uni.hideLoading();
        let err = JSON.parse(res);
        error(err);
        reject(err);
      },
      complete: () => {}
    });
  })
}

/**
 * 文件下载
 * @param {*} url 下载文件路径
 * @param {*} success 成功回调函数
 * @param {*} fail 失败回调函数
 * @returns 
 */
export function download(url, success, fail) {
  if (!url) return
  let downloadTask = uni.downloadFile({
    url: url,
    success: res => {
      if (res.statusCode === 200) {
        if (success) {
          success.call(null, res);
        }
      } else {
        if (fail) {
          fail.call(null, res);
        }
      }
    },
    fail: res => {
      let err = JSON.parse(res);
      error(err);
      if (fail) {
        fail.call(null, err)
      }
    },
    complete: () => {}
  })
  return downloadTask;
}

function error(res) {
  if (res.statusCode === 408 || res.statusCode === 401) {// 需要重新登录
    uni.removeStorageSync('token')
    uni.showToast({
      title: res.data,
      icon: "none"
    })
  } else if (res.statusCode === 404) {
    uni.showToast({
      title: "404,路径找不到:" + res.data.path,
      icon: "none"
    })
  } else if (res.statusCode === 503) {
    uni.showToast({
      title: "服务不可用",
      icon: "none"
    })
  } else if (res.statusCode === 504) {
    uni.showToast({
      title: "网络连接错误",
      icon: "none"
    })
  } else {
    uni.showToast({
      title: res.data,
      icon: "none"
    })
  }
}

export default导出的就是我们封装好的平常使用的发请求的方法,大家可以根据自己的项目按需修改。另外两个一个是上传文件(图片)、文件(图片)下载的封装的两个方法

里面引入了一个BASE_URL,这个BASE_URL就是我们请求服务器的地址,因为我们平时开发uniapp为了方便可能会直接运行到浏览器上面也即是H5,但这样的话会有跨域问题,如果运行在手机上(不管是真机运行,还是打包后安装到手机)都不会有跨域的问题,所以我们在config中这么设置: 

@/common/config.js 

let APP_SERVER_URL = "/api"

// #ifdef APP-PLUS
APP_SERVER_URL = 'http://localhost:3000'
// #endif

export default APP_SERVER_URL

我们加上#ifdef @endif条件编译,如果是运行在手机上的就会直接设置服务地址,如果不是就直接设置前缀 /api 

因为会有跨域问题才会设置 前缀 /api,然后manifest.json中配置 h5: {devServer: {proxy: {}}}等解决跨域问题: 

 manifest.json

{
  "h5": {
    "title": "xps",
    "domain": "demo1.jeeplus.org",
    "devServer": {
      "port": 3000,
      "disableHostCheck": true,
      "proxy": {
        "/api": {
          "target": "http://localhost:8080", // 需要跨域的域名
          "changeOrigin": true,
          "secure": false,
          "pathRewrite": {
            "^/api": ""
          }
        }
      }
    },
    "router": {
      "base": "/"
    },
    "optimization": {
      "treeShaking": {
        "enable": true
      }
    }
  }
}

 这篇就这么多,简单记录一下

猜你喜欢

转载自blog.csdn.net/m0_51431448/article/details/131542495
今日推荐