我正在尝试在我的第一个世博会项目中实现身份验证,但我在令牌过期方面遇到了困难。
这是我的身份验证上下文:
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createContext, useState } from "react";
export const AuthContext = createContext({
token: "",
isAuthenticated: false,
authenticate: (token) => {},
logout: () => {},
});
const AuthContextProvider = ({ children }) => {
const [authToken, setAuthToken] = useState();
const authenticate = (token) => {
setAuthToken(token);
AsyncStorage.setItem("token", token);
};
const logout = () => {
setAuthToken(null);
AsyncStorage.removeItem("token");
};
const value = {
token: authToken,
isAuthenticated: !!authToken,
authenticate: authenticate,
logout: logout,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
export default AuthContextProvider;
这是我的 index.js 文件,我在其中构建 axios 调用 (/src/api/index.js):
import axios from "axios";
import { API_BASE_URL } from "@env";
import AsyncStorage from "@react-native-async-storage/async-storage";
let getApiBaseURL = API_BASE_URL || "http://localhost:3000/api/v1";
const api = axios.create({
baseURL: getApiBaseURL,
headers: {
"Content-Type": "application/json",
},
});
api.interceptors.request.use(
async (config) => {
const token = await AsyncStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
Promise.reject(error);
}
);
export const exampleFetchData = async () => {
try {
const response = await api.get(`${API_BASE_URL}/employees`);
return response.data;
} catch (error) {
throw new Error("Failed to fetch data");
}
};
问题是:
我想使用拦截器来检查我的令牌是否有效。如果无效则触发注销。我不想使用间隔/超时来检查令牌有效性,而是在用户需要 API 调用时触发它。问题是我无法在功能组件主体之外使用上下文函数。
我怎样才能实现这个目标?我想在拦截器内调用注销。
我解决了它添加 setTimeout 但这不是我想要的
我也有同样的问题。你找到解决办法了吗?