微信小程序wx.request二次封装

这些天开始做小程序开发了在网络请求上发现了一些小问题,最终没忍住想了点办法把request封装了一下。下面来看看吧。

看项目代码时发现了下面几点问题:

网络请求都写在Page里,每个请求都要重复的写wx.request以及一些基础配置;
每个页面里都要处理相同类型的异常;
后端返的http status code为200以外时,并不能直接进入fail对应函数进行处理

针对这些问题,首先在项目utils目录里新建了一个http.js

const host = "http://www.week1.com:8888";

function request(url, data, method) {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中',
      duration: 3000
    })
    wx.request({
      url: host + url,
      data: data || {},
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        ‘token’:wx.getStorageSync('token')
      },
      method: method || 'GET',
      success: (res) => {
        wx.hideLoading()
        let statusCode = res.statusCode
        if (statusCode === 200 ) {
          resolve(res.data)
        } else {
          wx.showToast({
            title: '网络异常,请检查网络状态',
            icon: 'none',
            duration: 3000
        })
          reject(res)
        }
      },
      fail: (res) => {
        wx.hideLoading()
                wx.showToast({
                    title: '网络异常,请检查网络状态',
                    icon: 'none',
                    duration: 3000
                })
                reject(res)
      }
    })
  })
}

module.exports={
    request:request
}




之后在具体页面page.js直接对其进行引用

const http = require('../../utils/http');

 test(){
    http.request('/admin/vip/getdata')
  },

成功!!!

const domain = "http://www.tp.com:8888";

export default class Https{
//刷新token
 autoLogin(){
    return new Promise((resolve,reject)=>{
      wx.request({
        url: 'http://www.week2.com:7888/api/autoToken',
        success(res){
          console.log(res.data)
          wx.setStorageSync('token', res.data.token)
          wx.setStorageSync('expire', res.data.expire)
        }
      })
    })
  }
  
request(url,data,method){
  //获取token
   var token = wx.getStorageSync('token')
  //获取token过期时间
    var expire = wx.getStorageSync('expire')
  //当前时间戳
    var timestamp = new Date().getTime() 
    var time = timestamp / 1000
  // 如果过期时间  小于 当前时间 加 10 秒 则证明此token 已过期 准备提前刷新
     if( parseInt(expire) -  parseInt(time)   < 10 ){
     //调用刷新token接口 那时旧的token 还有效
        this.autoLogin().then(()=>{
          console.log(url)
            this.request(url, data, method);
        })
     }   
     
     var header = {
      'content-type': 'application/json'
    }
    if (token) {
         header = {
          'content-type': 'application/json',
          'token':token
         }
    }
    
  return new Promise((resolve,reject)=>{
    wx.request({
      url: domain+url,
      data: data || {},
      method: method ||'GET',
      success: (result) => {
         var statusCode = result.statusCode
         if(statusCode !== 200){
           wx.showToast({
             title: '网络异常,请重试',
             icon:"none",
             duration:3000
           })
         }
         resolve(result.data)
      },
      fail: (res) => {
        wx.showToast({
          title: '网络异常,请重试',
          icon:"none"
        })
        reject(res)
      }
      
    })
  })

}




}
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值