微信小程序请求封装

创建 config.js 文件管理环境

class Config {}

const version = '/v1.1.12'

Config.API_HOST = 'https://xxxxxx.com' + version //正式
//  Config.API_HOST = 'https://xxxxx.lsboot.cn' + version; //测试

export default Config

创建 base.js 封装需要用到的请求

import Config from './config.js';

class Base {
  /**
   * 静态方法, 获取请求有的header
   */
  static getHeader() {
    return {
      'Content-Type': 'application/json',
       'Authorization': wx.getStorageSync(TOKEN), 
      // 'Authorization': 'cdc8012982d44ae28bf5a9ede1b6152b',     
      'Accept-Language': 'zh'
    };
  }

  /**
   * 发起请求
   */
  request(params, noLogin) {
    return new Promise((resolve, reject) => {
      let url = Config.API_HOST + params.url;
      wx.request({
        url: Config.API_HOST + params.url,
        data: params.data || {},
        method: params.method || 'GET',
        header: Base.getHeader(),
        success: (res) => {
          // 根据需求 接口的返回状态码进行处理
          if (res.statusCode == 200) {
            let data = res.data;
            resolve(data);
          } else {
            console.info('statusCode', res.statusCode)
            // 401表示未登录
            if (res.statusCode == 401) {
              this.login().then((res) => {
                console.log('登录成功后重新发起请求--->>', res);
                this.request(params, noLogin).then(resolve).catch(reject);
              });
            } else {
              console.log('请求错误,请重试', res)
            }
          }
        },
        fail: (res) => {
          wx.showModal({
            title: '提示',
            content: "网络请求失败,请确保网络是否正常",
            showCancel: false,
            success: function(fail) {
              reject(res);
            }
          });
        }
      })
    })
  }

  /**
   * 发起get请求
   */
  get(url, data = {}) {
    return this.request({
      url: url,
      data: data
    });
  }

  /**
   * 发起post请求
   */
  post(url, data = {}) {
    return this.request({
      url: url,
      data: data,
      method: 'POST'
    });
  }

  /**
   * 登录
   */
  login() {
    let _this = this;
    return new Promise((resolve, reject) => {
      // 用户登录
      wx.login({
        success: function(login) {
          _this.request({
            url: '/wechatMiniLogin',
            data: {
              code: login.code,
            },
            method: 'POST'
          }).then((res) => {
            wx.setStorageSync(TOKEN, res.data.token);
            wx.setStorageSync(USER_INFO, res.data.userInfo);
            resolve(res);
          }).catch(reject);
        }
      })
    });
  }

  /**
   * uploadUrl: 上传的url
   * filePath: 文件地址
   * formData: 上传数据
   */
  uploadFile(uploadUrl, filePath, formData = {}) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: Config.API_HOST + uploadUrl,
        filePath: filePath,
        name: 'file',
        formData: formData,
        header: {
          'Content-Type': 'multipart/form-data',
          'X-Token': wx.getStorageSync(TOKEN)
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (res) => {
          wx.showModal({
            title: '提示',
            content: "网络请求失败,请确保网络是否正常",
            showCancel: false,
            success: function (fail) {
              reject(res);
            }
          });
        }
      })
    })
  }
}

export default Base;

创建api.js

import Base from './base.js'
import Config from './config.js'

export default class Api extends Base {
  getLoginUser(params) {
    return new Promise((resolve, reject) => {
      //里面的'/user/getLoginUser'更换成需要的请求的路径就好了
      this.post('/user/getLoginUser', params).then(res => {
        resolve(res)
      })
    })
  }
  updateUser(params) {
    return new Promise((resolve, reject) => {
      this.post('/user/updateUser', params).then(res => {
        resolve(res)
      })
    })
  }
}

页面中使用

import Api from '/utils/api.js'
var api = new Api()

//参数
let params = '123'
api.getLoginUser(params).then(res => {
  console.log(res)
}

猜你喜欢

转载自blog.csdn.net/weixin_45292658/article/details/107149832
今日推荐