小程序请求封装方法

微信小程序请求封装,http方法可直接放在app.js里
http(mathods,url, params) {
    var header = {
      'content-type': 'application/json',
      'token' : wx.getStorageSync('token') || '',
    }   //设置请求头,可以带其他后台验证参数,根据业务逻辑
    return new Promise(
      (resolve,reject) => {
        wx.showLoading({
          title: "正在加载中...",
        })
        wx.request({
          url: '', //请求地址
          method: mathods, //请求方法
          header: header,
          data: params || {}, //请求参数 
          success: res => {
            wx.hideLoading();
            resolve(res);
            //成功执行方法,参数值为res.data,直接将返回的数据传入
          },
          fail: function() {
            //请求失败
            wx.hideLoading();
            wx.showToast({
              title: '服务器错误,请稍后再试!',
              icon : 'none'
            })
            reject(err)
          },
        })
      }
    )
  }
 
 
页面上调用先引用app.js,在页面js最顶部获取 
const app = getApp();
 
页面上调用方法:
app.http('GET/POST/DELETE/...','接口地址',data).then((res)=>{
  //接收到后台返回的res
})

  

posted @ 2021-01-04 09:56  yanghaogogogo  阅读(135)  评论(0编辑  收藏  举报