情况:我发送一个请求来接收一些数据并收到令牌已过期的响应。接下来,我必须更新令牌并重新发送我一开始发送的请求。如何使用 redux-toolkit 和中间件来做到这一点?
用于捕获错误的中间件:
import { doRefreshToken } from "../reducers/user";
const TOKEN_EXPIRED_ERROR = "tokenExpiredException";
const tokenMiddleware = (api) => (next) => (action) => {
const result = next(action);
if (action.type === TOKEN_EXPIRED_ERROR) {
const refreshToken = localStorage.getItem("refreshToken");
api.dispatch(doRefreshToken({ refreshToken })).then(() => {
// dispatch new action
});
}
return result;
};
export default tokenMiddleware;
刷新令牌后发送的请求:
const getSmth = createAsyncThunk("user/getSmth ", async (_, { rejectWithValue }) => {
try {
const response = await api.get("/smth");
return response;
} catch (error) {
return rejectWithValue(error.response);
}
});
重要提示:不仅可以发送 getSmth 请求,还可以发送任何其他请求,您还需要在中间件中执行此操作