如何封装微信小程序的 wx.request() 请求

 先对 wx.request() 进行基本的请求封装,再继续封装 post 和 get 请求

//在utils/http.js文件中
/**
 * 请求相关的封装
 */
let baseUrl = "http://xxx.xxx.xx.xx:xx/"; // 接口地址
let header = {
  'content-type': 'application/x-www-form-urlencoded',
  'Authorization': wx.getStorageSync("token")?wx.getStorageSync("token"):''
}
/**
 * 封装请求
 */
function fetch(options) {
  if (options.loading) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + options.url,
      data: options.data,
      header: header,
      method: options.method,
      success: function(res) {
        if (options.loading) {
          wx.hideLoading()
        }        
        if (res.data.status != 0) { //根据自己的接口返回值进行判断
          // 重新登陆
          return false;
        }
        resolve(res.data); //把请求到的数据发到引用请求的地方
      },
      fail: function(err) {
        if (options.loading) {
          wx.hideLoading()
        }
        wx.showToast({
          title: "网络连接超时",
          icon: 'none',
          duration: 3000,
        })
      }
    })
  })
}

/**
 * POST 请求
 */
export function post(url, params, loading = true) {
  var option = {
    url: url,
    data: params,
    method: 'POST',
    loading
  }
  return fetch(option);
}

/**
 * GET请求
 */
export function get(urls, params, loading = true) {
  var option = {
    url: urls,
    data: params,
    method: 'GET',
    loading
  }
  return fetch(option);
}

使用

//先通过模块化引入
const util = require('../../utils/util.js')

//get请求
http.get('getuserInfo', params).then((res) =>{
  console.log(res)
})

//post请求
http.post('findDepartment', params).then( (res) =>{
  console.log(res);
}) 

//也可以使用 async 和 await,比如
async formSubmit(e) {
  let params = {
    name:e.detail.value.name
    passward:e.detail.value.passward
   }
 //let params = e.detail.value
  const res = await http.post('login',params)
   if(res.status===0){

   //将token和用户信息存到本地
   wx.setStorageSync('token', res.token);
   wx.setStorageSync('userinfo', res.userinfo);

     wx.showToast({
      title: res.message,
      icon: 'none',
      duration: 3000
    });
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值