原生微信小程序flyio封裝多baseURL配置請求,如同axios一樣非常爽利的使用api

 

1.下載 引入 flyio 基於 promise Javascript http請求的終極解決方案。也就是說,在任何能夠執行 Javascript 的環境,只要具有訪問網絡的能力,Fly都能運行在其上,提供統一的API。 fly下載地址

2.request.js 配置fly 請求體

// import Fly from 'flyio/dist/npm/wx';
const Fly = require("flyio.js");
const fly = new Fly();

//設置超時
fly.config.timeout = 20000;

// 獲取白名單
import whiteList from './whiteList';

//添加請求攔截器
fly.interceptors.request.use((request) => {
  // console.log('進入fly-request', request);
  wx.showLoading({
    'title': '加載中',
    'mask': true
  });
  // 不顯示加載頁面的接口
  if (whiteList.loading.indexOf(request.url) === -1) {
    // 隱藏loading遮罩
    wx.hideLoading();
  }
  // 請求資源服務器時,不添加token
  if (whiteList.nullHeaderToken.indexOf(request.url) !== -1) {
    request.timeout = 30000; // 請求超時
    request.headers = {
      'content-type': 'application/json',
      'X-Tag': 'flyio'
    };
    console.log('nullHeaderToken()')
    return request;
  }
  fly.lock();//鎖住請求
  // 延遲發請求 等 getStorageSync 存儲
  if (wx.getStorageSync('Authorization')) {
    // 給所有請求添加自定義header
    request.timeout = 30000;
    request.headers = {
      'content-type': 'application/json',
      'X-Tag': 'flyio',
      'Authorization': 'Bearer ' + wx.getStorageSync('Authorization')
    };
    fly.unlock();//解鎖請求
    return request;
  } else {
    console.log('沒有token跳轉登錄');
    setTimeout(() => {
      wx.redirectTo({
        url: '../login/login'
      });
    }, 300)
  }
}, (error, promise) => {
  // Do something with request error
  console.log(error); // for debug
  promise.reject(error)
});

//添加響應攔截器,響應攔截器會在then/catch處理之前執行
fly.interceptors.response.use(
  (response) => {
    wx.hideLoading();
    console.log('interceptors數據', response.data);
    //只將請求結果的data字段返回
    return response.data
  },
  (err, promise) => {
    wx.hideLoading();
    let msg = '';
    if (err.status === 0) {
      msg = '網絡連接異常'
    } else if (err.status === 1) {
      msg = '網絡連接超時'
    } else if (err.status === 401) {
      msg = '用戶未登錄'
    } else {
      if (err.response.data.message) {
        msg = err.response.data.message
      } else {
        msg = '請求數據失敗,請稍後再試'
      }
    }
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
    setTimeout(() => {
      console.log('fly.interceptors.err-toLogin')
      wx.redirectTo({
        url: '../login/login'
      });
    }, 500)
    return promise.resolve(err)
  }
);
// Vue.prototype.$http=fly //將fly實例掛在vue原型上

export default fly

 

3. baseUrlConfig.js 

/**
 *  定義各個API的 baseURL
 */
const baseURL = {
  'UAA': 'https://xxx1.com/uaa', // uaa 獲取token
  'IDC': 'http://xxx2:8580/idc-admin', // idc 相關業務
  'IDCtest': 'http://10.2.5.163:8790' // 本地開發
};
export default baseURL;

4.whiteList.js 白名單

export default {
  // 不顯示加載提示
  loading: [
    '/route/list'
  ],
  // 不重定向白名單
  route: [
    '/login'
  ],
  // 不帶token的url
  nullHeaderToken: [
    '/user/weChatLogin'
  ]
}

5.業務api  獲取token api

注意1 是 使用 fly.request

注意2  fly請求參數 是放置在 body 上 而不是 data:data

注意3 要使用另外 baseUrl 只需要寫上對應的 baseURL: baseURL.UAA 即可 

import fly from '../../request.js'
import baseURL from '../../baseUrlConfig.js'

// 圖表 表11 FleetList 查詢車隊列表
export function getReport11FleetList(query) {
  return fly.request({
    baseURL: baseURL.IDC,
    url: '/report11/getReport11FleetList?fleetName=' + query,
    method: 'get'
  })
}

// 圖表 表11 FleetName 查詢
export function getReport11ListByFleetName(data) {
  return fly.request({
    baseURL: baseURL.IDC,
    url: '/report11/getReport11ListByFleetName',
    method: 'post',
    body: data
  })
}

// uaa登錄
export function userWeChatLogin(data) {
  // console.log('userWeChatLogin()', data)
  return fly.request({
    baseURL: baseURL.UAA,
    url: '/user/weChatLogin',
    method: 'post',
    body: data
  })
}

6. 微信小程序裏使用api 舉例

import * as ChartsAPI from '../../../../wxapi/api/charts/charts.js'
// 根據自己的 文件放置 配置自己的文件引用路徑
userLogin: function() {
       wx.showLoading({
          title: '加載中',
       })
        const toParams = {
          "username": that.data.inputValueUsername,
          "password": that.data.inputValuePwd,
          "grantType": "password",
          "clientId": "devops",
          "clientSecret": "devops"
        }
        
        ChartsAPI.userWeChatLogin(toParams).then(res => {
          if (res.data && res.data.access_token) {
            wx.showToast({
              title: "登錄成功",
              icon: "success",
              duration: 1500
            })
            let resToken = res.data.access_token
            wx.setStorageSync('Authorization', resToken)
            setTimeout(() => {
              wx.redirectTo({
                url: '../index/index'
              })
            }, 1500)      
          }
          wx.hideLoading()
        }).catch(err => {
          wx.hideLoading()
          wx.showToast({
            title: "用戶或密碼錯誤",
            icon: "none",
            duration: 1500
          })
          console.log('error', err)
        })

}
        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章