小程序网络请求封装(二)

const app = getApp();
const base = app.globalData.base + '/api';

function requset(url, method, data, config={}){
  return new Promise((resolve, reject) => {
    wx.request({
      url: base + url, 
      method: method,
      data: data,
      dataType: 'json',
      header: {
        'content-type': 'application/json', // 默认值
        'openid': wx.getStorageSync('openid'),
        ...config.headers
      },
      success: function (res) {
        if(res.statusCode >=200 && res.statusCode<=300){
          // if(res.data.code != 1){
          //   wx.showModal({
          //     content: res.data.msg,
          //     showCancel: false,
          //   })
          // }
          resolve(res.data)
        }else{
          wx.showModal({
            content: '请求错误' + res.statusCode,
            showCancel: false,
          })
          reject(res)
        }
      },
      fail: function (err) {
        wx.showModal({
          content: '请求错误' + JSON.stringify(err),
          showCancel: false,
        })
        reject(err)
      }
    })
  })
}

export default {
  get: (url, data, config) => {
    return requset(url, 'GET', data, config)
  },
  post: (url, data, config) => {
    return requset(url, 'POST', data, config)
  }
}

猜你喜欢

转载自www.cnblogs.com/xiaozhou223/p/12671347.html