uniapp 开发微信小程序总结(二)axois 封装 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

uniapp 开发微信小程序总结(二)axois 封装

发表时间:2021-1-5

发布人:葵宇科技

浏览次数:85

1、安装 axois 和 axoisRetry 包

2、支持 在请求发生错误时,重新发送请求(一次),主要用于处理 token 过期、请求超时的情况。token过期时,会在获取新的token 后重新发送请求。

3、支持 接口是否需要带 token信息

4、请求失败 状态吗 401 时 和 非 200 会分别展示错误提示。

复制代码
  1 import store from '../store/index.js'
  2 import axios from "axios";
  3 import axiosRetry from 'axios-retry';
  4 
  5 let request = axios.create({
  6   baseURL: process.env.NODE_ENV === 'development'?"https://test":"https:// release"
  7   headers: {
  8     "Content-Type": "application/json"
  9   },
 10   timeout:2000 
 11 });
 12 axiosRetry(request, {
 13   retries: 1,                       // 设置自动发送请求次数
 14   retryDelay: (retryCount) => {
 15     return retryCount * 2000;      // 重复请求延迟
 16   },
 17   shouldResetTimeout: true,       //  重置超时时间
 18   retryCondition: async (error) => {
 19     //true为打开自动发送请求,false为关闭自动发送请求
 20     if(error.message.includes("status code 401")){
 21         await store.dispatch("login/onGetUserInfo",{},{root:true});
 22         return true
 23     }else if (error.message.includes("timeout")) {
 24         return true;
 25     } else {
 26       return false;
 27     };
 28   }
 29 })
 30 request.interceptors.request.use(
 31   config => {
 32       try {
 33          uni.showNavigationBarLoading()
 34         const token = uni.getStorageSync('token');
 35         if(config.needAuth === false){
 36             config.headers.authorization = ""
 37         } else if (token) {
 38           // 判断是否存在token,如果存在的话,则每个http header都加上token
 39           config.headers.authorization = token; //Authorization是登录接口返回
 40         }
 41         config.headers.type = "user"; // type:user   是固定的
 42         return config;
 43         
 44       } catch (e) {
 45         uni.hideNavigationBarLoading()
 46           uni.showToast({
 47               title: '发生错误,请稍后重试',
 48               position: 'center',
 49               icon: 'none',
 50               duration: 2000
 51           })
 52       }
 53   },
 54   err => {
 55     uni.hideLoading()
 56     uni.hideNavigationBarLoading()
 57     return Promise.reject(err);
 58   }
 59 );
 60 // http response 拦截器
 61 request.interceptors.response.use(
 62   response => {
 63     //拦截响应,做统一处理
 64     if(response.data.code != 200){
 65         uni.hideLoading()
 66         uni.showToast({
 67             title: response.data.msg,
 68             icon:"none",
 69             duration: 2000
 70         })
 71         if(process.env.NODE_ENV === 'development'){
 72             console.error(response.data.msg)
 73         }
 74     }
 75     uni.hideNavigationBarLoading()
 76     return response;
 77   },
 78   //接口错误状态处理,也就是说无响应时的处理
 79   error => {
 80     uni.hideLoading()
 81     uni.hideNavigationBarLoading()
 82     const {
 83       response: { status, errMsg: statusText, data: {message}}
 84     } = error;
 85     const token = uni.getStorageSync('token');
 86     if (status == 401&&token) {// 登录过期处理
 87     uni.getSetting({
 88         success: async function(t) {
 89             if(!t.authSetting["scope.userInfo"]){
 90                 uni.clearStorageSync()
 91                 store.commit("login/CHANGELOGINSTATE",{loginState:false},{root:true})
 92                 if(!store.state.login.isShowLogin){
 93                     store.commit("login/GETLOGINPOPUP",{},{root:true})
 94                 }
 95                 uni.showToast({
 96                     title: '登录已过期,请重新登录',
 97                     icon: 'none',
 98                     duration: 2000 
 99                 })
100             }
101         }
102     })
103     }else{
104         uni.showToast({
105             title: `请求错误,请稍后重试`,
106             position: 'center',
107             icon: 'none',
108             duration: 2000
109         })
110         console.error(`请求错误${status||''}:${statusText||message||''}`)
111     }
112     return Promise.reject(error); // 返回接口返回的错误信息
113   }
114 );
115 //真机获取  
116 axios.defaults.adapter = function (config) {  
117     return new Promise((resolve, reject) => {  
118         var settle = require('axios/lib/core/settle');  
119         var buildURL = require('axios/lib/helpers/buildURL');  
120         uni.request({  
121             method: config.method.toUpperCase(),  
122             url: buildURL(config.baseURL + config.url, config.params, config.paramsSerializer),  
123             header: config.headers,  
124             data: config.data,  
125             dataType: config.dataType,  
126             responseType: config.responseType,  
127             sslVerify: config.sslVerify,  
128             complete:function complete(response){  
129                 response = {  
130                   data: response.data,  
131                   status: response.statusCode,  
132                   errMsg: response.errMsg,  
133                   header: response.header,  
134                   config: config  
135                 };  
136 
137             settle(resolve, reject, response);  
138             }  
139         })  
140     })  
141 }
142 export default request;
复制代码

相关案例查看更多