拦截器、钩子函数

一、拦截器

// axios 拦截器
axios.interceptors.request.use(config => {
    let token = localStorage.getItem("token")
    if (token) {
        config.headers.Authorization = token
    }
    return config
}, error => {
    router.push("/clogin")
    return Promise.reject(error)
})

二、白名单

//设置白名单
router.beforeEach((to, from, next) => {
    let white = ["/clogin"]
    let pathlist = JSON.parse(localStorage.getItem("pagelist"))
    if (pathlist) {
        for (var i = 0; i < pathlist.length; i++) {
            white.push(pathlist[i])
        }
        if (white.includes(to.path)) {
            next()
        } else {
            alert("您没有权限")
        }
    } else {
        if (white.includes(to.path)) {
            next()
        } else {
            alert("您没有权限")
       }
    }
})

三、分装axios

//分装的axios
const myaxios = function(url, method, data = {}) {
    return new Promise((resolve) => {
        if (method == 'get' || method == 'delete') {
            axios({ 'url': url, 'method': method, 'params': qs.stringify(data) }).then(res => {
                return resolve(res.data)
            })
        } else {

            axios({
                'url': url,
                'method': method,
                'data': data
            }).then(res => {
                return resolve(res.data)
            })
        }
    })
}
export default myaxios;

四、钩子函数

# #钩子函数限制后端接口
@app.before_request
def before_request():
    #设置白名 除了登录注册 其余全部需要tokenh
    whitelist = ['/users/login/']
    #如果访问的接口没有在白名单里
    if request.path not in whitelist:
        #获取token 获取到进行下一不没有就提示没权访问   应为token报错看不懂直接返回一个jsonify的语句
        
        try:
            token = request.headers['Authorization']
            print(token)
        except:
            return jsonify({'code':400301,'mes':'无权访问'})
        #获取用户的后台权限
        #判断用户token是否合法
        if myjwt.jwt_check == False:
            return jsonify({'code':400301,'mes':'token不合法'})
        
        #解析token  拿到id  查询用户后台权限 没有则不合法  {'data': {'mobile': '13212345678', 'userid': 1, 'name': '李思'}}
        datapay = myjwt.jwt_decode(token)
        userid = datapay['data']['userid']
        #分装在set中的key  取出了列表
        key = 'interface'+str(userid)
        postlist = r.set_get(key)
        print(postlist)
        if  request.path not in postlist:
            return jsonify({'code':400301,'mes':'无权访问'})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值