【react】通过PubSubJS插件实现token失效时回到登录页面

求库我用的axios,为了对axios封装所以建立了一个request.js,方便添加token和处理后端返回的状态码。
当后端返回的状态码为401,则表示token失效了,需要让用户重新登陆,但是由于使用的路由插件为react-router-dom v5版本,没有办法像vue一样直接在request里直接引用router,或使用history进行跳转,所以使用PubSubJS,利用事件的发布和订阅来完成退回登录页面的操作。

  npm install pubsub-js --save  // 安装插件
  import PubSub from 'pubsub-js' //引入
  PubSub.publish('delete', data) //发布消息
  PubSub.subscribe('delete', function(data){ }); //订阅

request.js

import axios from 'axios'
import { message } from 'antd';
import userInfo from "./userInfo";
import PubSub from 'pubsub-js'

let request = axios.create({
    baseURL:'http://xxxxxx:8099/',
    timeout:5000
})
//拦截响应
request.interceptors.response.use((response)=>{

        if (response.data && !response.data.status && response.data.code == 401) {
   			// 当状态码是401时,发布一个logout事件,第一个参数是自定义事件名,第二个是携带的参数
            PubSub.publish('logout', response.data.code);
            message.error(response.data.msg)
            throw new Error();
        }else if(response.data.code === 400 || response.data.code === 404){
            message.error(response.data.msg);
            throw new Error();
        }else if(response.data.code === 500){
            message.error(response.data.msg);
            throw new Error();
        }
        return response.data
    },function (error){
        message.error(error.data.msg)
        //对响应的错误做点什么
        return Promise.reject(error);
    }
)

export default request

监听logout事件

建议放在APP.js中。
不要使用一般函数,而要利用箭头函数的 this 指针是外层函数的this这一特性。

    // 渲染完成
    componentDidMount() {
        PubSub.subscribe('logout',(data)=>{
        	// 具体的退出操作
            this.props.history.replace('/login');
        })
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值