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
  })
}

// 单个api 针对的相应 各项配置
// 获取 token 登录 
export function userLogin(data) {
  return fly.request({
    headers: {
      'Authorization': 'Basic b3A6b3A=',
    }, // headers 配置
    timeout: '30000', // 超时时间
    baseURL: baseURL.IDC, // 请求后端地址
    url: '/auth/form', // 请求api
    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)
        })

}
        

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐