微信小程序封装的网络请求和上传文件

header.js

class Header {
    'content-type' = 'application/x-www-form-urlencoded;charset=UTF-8'
}

export default Header

request.js

  import Header from './header'

  class Request {
    baseApi = 'https://xxx.xxx.xxx/xxx/'; //域名
    header = new Header();
    post (params, path) {
      
      return new Promise((resolve, reject) => {
        wx.showLoading({
          title: '加载中...',
        })
        wx.request({
          url: this.baseApi + path, //仅为示例,并非真实的接口地址
          data: params,
          header: this.header,
          method: 'POST',
          success: res => {
            resolve(res)
            wx.hideLoading();
          },
          fail: rej => {
            wx.hideLoading();
            reject(rej)
          }
        })
      })
    }

    get(params, path) {
      return new Promise((resolve, reject) => {
        wx.showLoading({
          title: '加载中...',
        })
        wx.request({
          url: this.baseApi + path, //仅为示例,并非真实的接口地址
          data: params,
          header: this.header,
          method: 'GET',
          success: res => {
            wx.hideLoading()
            resolve(res)
          },
          fail: rej => {
            wx.hideLoading()
            reject(rej)
          }
        })
      })
    }

    json(params, path) {
      return new Promise((resolve, reject) => {
        wx.showLoading({
          title: '加载中...',
        })
        wx.request({
          url: this.baseApi + path, //仅为示例,并非真实的接口地址
          data: params,
          header:{'content-type': 'application/json'},
          method: 'POST',
          dataType: 'json',
          success: res => {
            resolve(res)
            wx.hideLoading()
          },
          fail: rej => {
            reject(rej)
            wx.hideLoading()
          }
        })
      })
    }

    formData(path, filePath, fileKey) { /** 用于上传文件 */
      return new Promise((resolve, reject) => {
        wx.showLoading({
          title: '上传中...',
        })
        wx.uploadFile({
          header: {
            'content-type':'multipart/form-data'
          },
          url: this.baseApi + path, //仅为示例,非真实的接口地址
          filePath: filePath,
          name: fileKey,
          success: res => {
            resolve(res);
            wx.hideLoading();
          },
          fail: rej => {
            reject(rej);
            wx.hideLoading();
          }
        })
      })
    }

  }

  export default Request

你可能感兴趣的:(微信小程序封装的网络请求和上传文件)