首页 > 编程语言 >小程序封装一个Request 请求

小程序封装一个Request 请求

时间:2022-11-16 11:11:44浏览次数:48  
标签:function code 封装 请求 res Request token data wx

'use strict'
import {
  getToken
} from './auth'

const baseUrl1 = 'https://xxx'.  // 域名地址


var Request = function (url, data, method="get",header,code=200,isLogin=false) {
  var baseUrl = url.indexOf("http") == -1?baseUrl1:''
//   var baseUrl = url.indexOf("https") == -1?baseUrl1:'' //正式版本进入https
  var promise = new Promise(function (resolve, reject) {
    wx.request({
      url: `${baseUrl}${url}`,
      data: data,
      method: method,
    //   header: {
    //     'Authorization': token ? token : ''
    //   },
      header: getToken() ? {
        'token':getToken()
      } : header,
      success: function success(res) {
        console.log(res)
        if (res.data) {
          if (res.data.code == 100 || res.data.code == 200 || res.data.code == code) {
            resolve({
              msg: res.data.msg,
              code: res.data.code,
              data: res.data.data||res.data.rows
            })
          } else if (res.data.code == 0) {
            resolve({
              code: res.data.code,
              data: res.data.result
            })
          }else if (res.data.code == 401) {
            wx.showToast({
              title: '授权失败,请重新登录!',
              icon: 'none',
              duration: 2000,
              mask: true
            });
            wx.removeStorageSync("userInfo")
            wx.removeStorageSync('menuList')
            wx.removeStorageSync('access-token')
            setTimeout(function () {
              wx.redirectTo({
                url: '../login/index'
              })
            }, 1000)
          } else {
            reject({
              errormsg: res.data.msg,
              code: res.data.code
            })
            wx.hideLoading();
            if(!isLogin){
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000,
                mask: true
              });
            }
          }
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '服务器错误,请稍后重试!001',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
      fail: function fail(res) {
        wx.hideLoading();
        console.log("进到失败里面了哦,请注意")
        wx.showToast({
          title: '服务器错误,请稍后重试!003',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    })
  })
  return promise
}

module.exports = {
  apiRequest: Request
}

auth.js

const TokenKey = 'access-token'

export function getToken() {
  return wx.getStorageSync(TokenKey)
}

export function setToken(token) {
  return wx.setStorageSync(TokenKey, token)
}

export function removeToken() {
  return wx.removeStorageSync(TokenKey)
}

 

标签:function,code,封装,请求,res,Request,token,data,wx
From: https://www.cnblogs.com/panax/p/16895194.html

相关文章