我正在创建Redux中间件,以在令牌过期之前在任何请求之前刷新令牌。
问题在于,在第一次调用后,我总是得到error 400 bad request
,但是如果再次调用(这是分页请求),它会正常工作,因为令牌已刷新。
我注意到,在引入新令牌之前和设置新的Axios授权标头之前,会触发Axios请求,因此我尝试使中间件异步等待,但是仍然没有运气...
import {
getJWT,
isTokenExpired
} from "../util/helpers";
import Cookies from "js-cookie";
import axios from "axios";
const refreshTokenMiddleware = store => next => async action => {
if (!action.excludeFromRefresh) {
const token = getJWT();
if (token && isTokenExpired()) {
try {
const { data } = await axios.post("auth/refresh");
axios.defaults.headers.common[
"Authorization"
] = `Bearer ${data.data.access_token}`;
Cookies.set("AppToken", data.data.access_token);
next(action);
} catch (error) {
console.log(error);
}
} else {
next(action);
}
} else {
next(action);
}
};
export default refreshTokenMiddleware;
我还怀疑第一次使用旧令牌调用Axios请求。
我在这里做什么错了?
====================
由于中间件无法捕获axios请求,因此我试图将所有中间件放在一起并实现axios拦截器...
axios.interceptors.request.use(
function(config) {
// Do something before request is sent
if (
config.url !== "auth/refresh" &&
config.url !== "auth/login" &&
config.url !== "auth/register"
) {
const token = getJWT();
if (token && isTokenExpired()) {
axios.post("auth/refresh").then(res => {
config.headers.Authorization = `Bearer ${res.data.data.access_token}`;
console.log(
"Inside the refresh in interceptor",
res.data.data.access_token
);
return config;
});
}
}
return config;
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
但这似乎也不起作用,该请求在第一次使用Authorization标头中的旧Token触发。
我该怎么办?
答案 0 :(得分:0)
乍一看,此if
语句有某种错误,因为您尝试一次检查url是否具有三个不同的值,我认为您应该在此处使用||
运算符。
答案 1 :(得分:0)
对于可能对本文感兴趣的任何人,我都设法使用此Axios interceptor
解决了我的问题...
https://gist.github.com/Godofbrowser/bf118322301af3fc334437c683887c5f