微信小程序接口封装、原生接口封装、request、promise封装

相信大家在做微信小程序的时候会有很多地方需要调用接口,就和pc以及手机端一样,多个页面多次调用会有很多状态,那为了节省大家的开发时间就会需要给请求的接口做一些简单封装,便于开发,在这里我用了两个js,一个js封装的是方法名,另外一个是接口名,统一管理

下面这个是统一的接口方法封装

const baseURL = "接口名";
const request = params => {
  const token = wx.getStorageSync("token").token;
  return new Promise((resolve, reject) => {
    wx.showLoading();
    wx.request({
      url: baseURL + params.url,
      data: params.data,
      method: params.method,
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
        token: token
      },
      success(res) {
        const pages = getCurrentPages();
        // const app = getApp();
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data);
          } else if (res.data.code === 401) {
            wx.navigateTo({
              url: '/pages/login/index',
            })
          } else {
            if (res.data.code == 1104) {
              wx.clearStorageSync()
              wx.redirectTo({
                url: '/pages/login/index',
              })
            } else {
              reject(res.data);
            }
          }
        }
      },
      fail(err) {
        reject(err);
      },
      complete() {
        wx.hideLoading();
      }
    });
  });
};
const _upload = (filePath, type) => {
  const token = wx.getStorageSync("token").access_token;
  return new Promise((resolve, reject) => {
    wx.showLoading();
    wx.uploadFile({
      url: baseURL + "upload_file", //仅为示例,非真实的接口地址
      filePath,
      name: "file",
      header: {
        authorization: token ? "Bearer " + token : undefined
      },
      formData: {
        type
      },
      success(res) {
        resolve(JSON.parse(res.data));
      },
      fail(err) {
        reject(err);
      },
      complete() {
        wx.hideLoading();
      }
    });
  });
};
const _get = (url, data) => {
  return request({
    url,
    data,
    method: "GET"
  });
};
const _post = (url, data) => {
  return request({
    url,
    data,
    method: "POST"
  });
};
const _put = (url, data) => {
  return request({
    url,
    data,
    method: "PUT"
  });
};
const _delete = (url, data) => {
  return request({
    url,
    data,
    method: "DELETE"
  });
};
module.exports = {
  baseURL,
  _get,
  _post,
  _put,
  _delete,
  _upload
};

下面这个是统一的接口管理

import { _get, _post, _put, _delete, _upload } from "./request";

// 图片上传
const getUploadImg = data => {
  return _post("接口名", data);
};
module.exports = {
  getUploadImg
};

封装的比较简单粗暴,不过通俗易懂

使用的时候直接在页面引入就可以