es6 简单封装request请求

时间:2019-10-25 14:42:57   收藏:0   阅读:538

es6 封装request请求

 

为了使代码更精简,便于理解和维护,使用 new Promise方法对request请求进行封装

new Promise(resolve, reject) 含有两个参数

resolve :成功时的调用

reject:失败时的调用

app.js中封装reeuqst请求

App({
  onLaunch: function(options) {
  },
  globalData: {
    localUrl: "https://www.baidu.com",
  },
  request(api, params, method) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.globalData.localDoctorUrl + api,
        data: params,
        header: {
          ‘content-type‘: ‘application/x-www-form-urlencoded‘,
          ‘csrf-csrf‘: ‘csrf-csrf‘,
        },
        method: method ? method : ‘get‘,
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          wx.showToast({
            title: err,
            icon: ‘none‘
          });
          reject("请求失败")
        }
      })
    })
  },
})

 

在其他需要用到请求的页面直接引用

 
const app=getApp();
 
//request请求
 
app.request("接口地址","参数","post/get").then(res=>{
 
//请求成功的处理
 
}).catch(err=>{
 
//请求失败的处理
 
})

 

 

原文:https://www.cnblogs.com/tt-ff/p/11737719.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!