reactjs - React 路由器 + Axios 拦截器。如何进行重定向?
问题描述
我有一个 axios 拦截器,当用户被强制注销(因为令牌过期)时,我想回到我的主页。
我不确定如何将反应路由器传递给它。我正在使用 mobx,但不确定这是否能帮助我解决这个问题。
export const axiosInstance = axios.create({
baseURL: 'https://localhost:44391/api',
timeout: 5000,
contentType: "application/json",
Authorization: getAuthToken()
})
axiosInstance.interceptors.response.use(function (response) {
return response;
}, function (error) {
const originalRequest = error.config;
if(error.code != "ECONNABORTED" && error.response.status === 401 && !originalRequest._retry){
originalRequest._retry = true;
return axiosInstance.post("/tokens/auth",{
"refreshToken": getRefreshToken(),
"grantType": "refresh_token"
}).then(response => {
localStorage.authentication = JSON.stringify(response.data);
updateAuthInstant();
return axiosInstance(originalRequest)
});
}
return Promise.reject(error);
});
解决方案
您应该添加历史npm 包。有了它,您可以创建浏览器历史记录并在应用程序的其他位置使用它。
例如:
// routing.js
import createHistory from 'history/createBrowserHistory';
export const history = createHistory();
在包含您的路线的组件中。
import { Route, Router } from 'react-router-dom';
import { history } from './routing.js';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
const Routes = () => (
<Router history={history}>
<div>
<Route exact path='/route1' component={ComponentA} />
<Route exact path='/route2' component={ComponentB} />
</div>
</Router>
);
在您要控制路由的其他文件中:
import { history } from './routing.js';
function changeRoute() {
// things happening here..
history.push('/route2');
}
调用changeRoute()
时路径会更新为/route2
并将ComponentB
被渲染。
推荐阅读
- terminal - 是否可以在 macOS 终端中获取文件所有者 url 元数据?
- git - git svn fetch '错误运行上下文:软件导致连接中止...'
- python - Python:将 .txt 文件加载到不同的列表中
- postgresql - Postgres 更新 JSON 列中所有记录的第一条记录
- javascript - 未捕获的 DOMException:无法在“文档”上执行“querySelector”:“#”不是有效的选择器
- c - 我可以打开一个伪终端作为奇校验吗?我不断重新调整无效参数
- javascript - 如何使用 Javascript 通过 selenium 3.6.0 使用另一个配置文件打开 Firefox 浏览器
- angular - 淡入和推底动画
- gitlab - .gitlab-ci.yml 中的条件 after_script
- hyperledger-fabric - 卸载 Hyperledger-composer 后出现 npm 安装错误 - 区块链