小程序封装请求request 完整版


## 当前的js要放在跟page同级目录

  **//定义公共url**
const baseUrl = "公共URL"
let ajaxTImes = 0 

export const get=(params)=>{
  let token = wx.getStorageSync('Authori-zation')
  ajaxTImes++
  wx.showLoading({
    title: '拼命加载中',
    mask:true
  })
  return new Promise((resolve,reject)=>{
    wx.request({
      ...params,
      url:baseUrl+params.url,
      header: {
        "Content-Type": "application/json;charset=UTF-8", //请求头类型
        'Authori-zation':token   //token要不要放请求头 请求头的类型

      },
      method:"GET",
      success:(res)=>{
        // console.log(res.data)
        if(res.data.status == 200){
          resolve(res)
        }else if(res.data.status == 410000 ){//判断token失效之后返回值再次默认授权
          wx.login({
            success(res) {
              // console.log(res)
              let code = res.code
              wx.getUserInfo({
                success(res) {
                  wx.request({
                    url: '后端给的接口地址',
                    method: 'POST',
                    data: {
                      "code": code,
                      "login_type":"routine" ,
                      "encryptedData": res.encryptedData,
                      "iv": res.iv
                    },
                    header: {
                      "Content-Type": "application/json;charset=UTF-8",
                    },
                    success(res) {
                  // console.log( res.data)
               if (res.data.status==200) {//判断是否成功
                    wx.setStorage({
                      key: "Authori-zation",//成功就把返回的token放到缓存里面
                      data: res.data.data.token,
                    })
               }
                    }
                  })
                }
              })
            }
          })
        }else{
          wx.showToast({       //失败返回失败原因
            title: res.data.msg,
            icon:"none",
            duration:1500
          })
        }
      },
      fail:(err)=>{ 
        reject(err);
      },
      complete:()=>{
        ajaxTImes--
        if(ajaxTImes==0){
          wx.hideLoading()
        }
      }
    });
  })
}
export const post=(params)=>{
  let token=wx.getStorageSync('Authori-zation')
  ajaxTImes++
  wx.showLoading({
    title: '拼命加载中',
    mask:true
  })
  return new Promise((resolve,reject)=>{
    wx.request({
      ...params,
      url:baseUrl+params.url,
      header: {
        "Content-Type": "application/json;charset=UTF-8", //请求头类型
        'Authori-zation':token   //token要不要放请求头 请求头的类型

      },
      method:"POST",
      success:(res)=>{
        if(res.data.status == 200){
          resolve(res)
        }else if(res.data.status == 410000 ){
          wx.login({
            success(res) {
              // console.log(res)
              let code = res.code
              wx.getUserInfo({
                success(res) {
                  wx.request({
                    url: '后端给的接口地址',
                    method: 'POST',
                    data: {//传给后端的数据
                      "code": code,
                      "login_type":"routine" ,
                      "encryptedData": res.encryptedData,
                      "iv": res.iv
                    },
                    header: {
                      "Content-Type": "application/json;charset=UTF-8",
                    },
                    success(res) {
                      if (res.data.status==200) {//判断是否成功
                    wx.setStorage({
                      key: "Authori-zation",//成功就把返回的token放到缓存里面
                      data: res.data.data.token,
                            })
                      }
                    }
                  })
                }
              })
            }
          })
        }else{                   //失败返回失败原因
          wx.showToast({
            title: res.data.msg,
            icon:"none",
            duration:1500
          })
        }
      },
      fail:(err)=>{ 
        reject(err);
      },
      complete:()=>{
        ajaxTImes--
        if(ajaxTImes==0){
          wx.hideLoading()
        }
      }
    });
  })
}

使用方式

**在需要使用的页面引入即可**
import {post,get} from "../../request/request.js";//index.js里面引入

 async 方法名() {
    let _that = this
    try {
      const res = await get(或者post)({
        url: 'url',
      })
      console.log(res)
      if (res.data.status == 200) {  //成功
        console.log(res.data)
      }else{
        wx.showToast({            //失败
          title: res.data.msg,
          icon:'none',
          duration:3000
        })
      }

    } catch (error) {   //这步操作防止用户断网的时候做提醒
      if (error.errMsg == "request:fail ") {
        wx.showToast({
          title: "无网络链接",
          icon: 'none',
          duration: 1000
        })
      }
    }
  },





// 或者


/**
 * 封封微信的的wx.request
 * method: 请求方式
 * url: 请求地址
 * data: 传递的参数
 */

function request(objData) {
  const app = getApp()
  app.globalData.token = wx.getStorageSync('token')
  // console.log('request', app)
  const {
    url,
    data = {},
    method = "GET"
  } = objData;
  return new Promise(function (resolve, reject) {
    wx.request({
      url: app.globalData.host + url,
      data: data,
      method: method,
      header: {
        "content-type": "application/json",
        'Accept': "application/json, text/plain, */*",
        "XX-Device-Type": "LB_STAFF_WX_MINI",
        "X-Access-Token": app.globalData.token,
      },
      success: function (res) {
        if (res.data.success !== undefined && !res.data.success) {
          if (res.data.code === 202 || res.data.code === 4001002) {
            app.toastError(res.data.message);
            setTimeout(() => {
              // wx.clearStorageSync();
              app.globalData.unLogin = false;
              wx.reLaunch({
                url: "/pages/index/index",
              });
            }, 1000);
            reject(res.data)
          } else if (res.data.code === 40020401) {
            reject(res.data)
          } else {
            console.log("请求失败了", res.data.message, url, data);
            app.toastError(res.data.message);
            reject(res.data)
          }
        } else {
          resolve(res.data);
        }
      },
      fail: function (err) {
        app.toastError("无法连接网络");
        reject(err);
      },
      complete: function (res) {
        // resolve(res.data)
      },
    });
  });
}

module.exports = {
  request,
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值