uniapp request encapsulation

Let’s just record it briefly here. I have been working on uniapp for a long time. I hope that when I change to another project next time, I can copy it directly from here and use it.

Everyone knows that uni.request() provided to us in uniapp is used for us to send requests. It has three callback functions: success, fail, and complete. If you write uni.request every time you send a request, the whole project will come down. It's super cumbersome, and it's not easy to maintain, it's not easy to unify, and the code is not very readable. So here we use Promise for secondary encapsulation, just call the method directly to pass in the interface address, parameters, etc. Don’t talk nonsense, let’s directly upload the code below:

Here I created a new common folder in the root directory of the project, and created a new request.js in it 

That is @/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"
    })
  }
}

The export default export is the method of sending requests that we packaged and usually used, and you can modify it according to your own projects. The other two are two methods of encapsulation of uploading files (pictures) and downloading files (pictures)

A BASE_URL is introduced in it. This BASE_URL is the address of our request server, because we usually develop uniapp for convenience and may run directly on the browser, which is H5, but in this case there will be cross-domain problems. If it runs on a mobile phone ( Whether it is running on a real machine or packaged and installed on a mobile phone), there will be no cross-domain problems, so we set this in the config: 

@/common/config.js 

let APP_SERVER_URL = "/api"

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

export default APP_SERVER_URL

We add #ifdef @endif conditional compilation, if it is running on the mobile phone, it will directly set the service address, if not, directly set the prefix /api 

The prefix /api is set because there will be cross-domain problems, and then configure h5 in manifest.json: {devServer: {proxy: {}}} to solve cross-domain problems: 

 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
      }
    }
  }
}

 That's all for this article, just record it

Guess you like

Origin blog.csdn.net/m0_51431448/article/details/131542495