The web utility classes in UNI-App were documented in the previous article, but here is another implementation – the fly.js wrapper API utility class

Fly.js is a promising, lightweight and powerful Javascript HTTP web library for multiple development references, with support for request/response interceptors and automatic conversion of JSON data….

1. Install it first

npm install flyio / yarn add flyio
Copy the code

2. Encapsulate the tool classes

  import Fly from "flyio/dist/npm/wx";

  let fly = new Fly,
    hostMap = {
      'development': 'https://www.baidu.test.com'};// Configure the request base address
  fly.config.baseURL = hostMap[process.env.NODE_ENV] || 'https://www.baidu.com';

  fly.config.timeout = 10000;

  // // Add request interceptor
  fly.interceptors.request.use((config, promise) = > {
      const AUTH_TOKEN = wx.getStorageSync('AUTH_TOKEN');

      if(! AUTH_TOKEN){console.error('TOKEN not obtained');
      }

      config.headers.token = AUTH_TOKEN;
      return config;
  })

  fly.interceptors.response.use(
      (response, promise) = > {
          if(response.data && response.data.success){
              return response.data.data;
          }else{
              if(response.data && (response.data.code == '10000005' || response.data.code == '10000003')) {let pages = getCurrentPages();
                  let currentPage = pages[pages.length- 1];

                  if(currentPage.route ! ='pages/daka/homePage/main'){
                    wx.navigateTo({
                      url: '/pages/daka/homePage/main'
                    });
                    return promise.reject(' '); }}else{
                  if(response.data && response.data.message){
                      wx.showModal({
                          title: 'tip'.showCancel: false.content: response.data && response.data.message
                      });
                  }
                  return promise.reject(' ');
              }
          }
      },
      (err, promise) => {
          wx.hideLoading();
          console.warn(err);
          wx.showModal({
               title: 'tip'.showCancel: false.content: 'Network is not smooth, please try again later! '}); })export default fly
Copy the code

Calling utility classes

import fly from "./fly";

const Api = { 
    login: param= > {
      return fly.get(`api/loign?${param}`); }}export default Api
Copy the code