flyio 请求增加token验证

网址:https://wendux.github.io/dist/
第一步,安装flyio:

npm install flyio  
npm install qs  //安装qs模块,用来见参数转化为url格式,

第二步,新建文件命名为request.js,封装token请求:

import Vue from 'vue'
// import fly from 'flyio' 此方式引入是fly实例
var Fly=require("flyio/dist/npm/fly")  //此方式是引入Fly构造函数
import qs from 'qs'

const BASE_URL = 'http://192.168.0.1/';  
const IMG_LOAD = 'http://192.168.0.1/';
const IMG_URL = 'http://192.168.0.1/';

var fly = new Fly()
fly.config.baseURL = BASE_URL; 
fly.config.IMG_URL = IMG_URL; 
fly.config.IMG_LOAD = IMG_LOAD; 
fly.config.timeout = 100000;

var newFly = new Fly()
newFly.config = fly.config

let loginInfo = localStorage.getItem("loginInfo")
if(loginInfo){
    loginInfo = JSON.parse(loginInfo)
}else{
    loginInfo = {
        username:'',
        pass:'',
    }
}
fly.interceptors.request.use(function(request) {
                    
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    
    if(request.url != '/login.php' && request.url != '/register.php' && request.url != '/sendvercode.php'){
        request.headers['token'] = loginInfo.token;   //这里的 token 可与后端商量用大写或是小写
    }
    
    request.body = qs.stringify(request.body); 
});

fly.interceptors.response.use(function(response, promise) {
    //token失效,自动申请
    if(response.data.error == 'token错误' || response.data.error == 'token已失效'){
    
        return newFly.get('/login.php', {
            mobile:loginInfo.mobile,
            password: loginInfo.pass,
        }).then(function(res) {
            loginInfo = Object.assign(loginInfo,{
                token:res.data.data[0].token
            })
            localStorage.setItem("loginInfo",JSON.stringify(loginInfo))
            response.request.headers['token'] = res.data.data[0].token;
            //返回重新生成的请求
            return fly.request(response.request.url,qs.parse(response.request.body),{method:response.request.method});
        }).catch(function(err) {
        })
        
    }else{
        return promise.resolve(response);
    }
});


export default fly;

第三步,新建apis.js,封装apis:

import fly from './request.js';

export default{
    login:function(param){
        return fly.get('/login.php',param)
    },
    register:function(param){
        return fly.post('/register.php',param)
    },
    sendvercode:function(param){
        return fly.post('/sendvercode.php',param)
    }
}

第四步,APP.vue中挂载apis:

import apis from './assets/js/apis.js';
Vue.prototype.$apis = apis;

然后就可以正常开始使用了,token获取根据实际情况调整代码
例外封装apis方便接口管理,在uni app中封装的js可加入文件混淆列表,防止app反编译代码暴露

推荐阅读更多精彩内容