英文:
How to remove authentication token with react native?
问题
我有一个React Native应用。还有一个登出API调用。所以我现在尝试在React中实现登出API调用。我面临的问题是,在我调用API调用登出后,令牌不会被移除。但我在Swagger中进行了测试,它是有效的。当我触发API调用登出时,令牌已被移除。
所以我有一个服务:
export const logoutRequest = async () => {
try {
const response = await fetch("http://192.168.1.65:8000/api/user/logout/");
return await response.json();
} catch (error) {
console.log(error);
throw error;
}
};
和一个上下文:
const onLogout = () => {
logoutRequest();
};
以及调用onLogout的视图:
<AuthButton icon="email" mode="contained" onPress={() => onLogout()}>
Logout
</AuthButton>
为了传递令牌给其他API调用,我正在使用这个函数:
import AsyncStorage from "@react-native-async-storage/async-storage";
export const retrieveToken = async () => {
try {
const token = await AsyncStorage.getItem("Token");
return token;
} catch (error) {
return null;
}
};
问题:如何在React Native中移除身份验证令牌?
英文:
I have a react native app. And a logout api call. So I try now to implement the logout api call in react. And the problem I am facing is that the token will not be removed after I called the api call logout. But I tested in swagger and that works. The token have been removed when I trigger the api call logout.
So I have a service:
export const logoutRequest = async () => {
try {
const response = await fetch("http://192.168.1.65:8000/api/user/logout/");
return await response.json();
} catch (error) {
console.log(error);
throw error;
}
};
and a context:
const onLogout = () => {
logoutRequest();
};
and the view that calls the onLogout:
<AuthButton icon="email" mode="contained" onPress={() => onLogout()}>
Logout
</AuthButton>
and to pass the token for the other api data calls. I am using this function"
import AsyncStorage from "@react-native-async-storage/async-storage";
export const retrieveToken = async () => {
try {
const token = await AsyncStorage.getItem("Token");
return token;
} catch (error) {
return null;
}
};
Question: how to remove authentication token in react native?
答案1
得分: 1
用户成功登出后,应用程序应从异步存储中移除 token
。
export const removeToken = async () => {
try {
await AsyncStorage.removeItem("Token");
} catch (error) {
console.log("移除身份验证令牌失败:", error?.message);
}
};
然后,
export const logoutRequest = async () => {
try {
const response = await fetch("http://192.168.1.65:8000/api/user/logout/");
await removeToken();
return await response.json();
} catch (error) {
console.log(error);
throw error;
}
};
英文:
After the user logout successfully, the app should remove the token
from async storage.
export const removeToken = async () => {
try {
await AsyncStorage.removeItem("Token");
} catch (error) {
console.log("Renove authentication token failed :", error?.message);
}
};
Then
export const logoutRequest = async () => {
try {
const response = await fetch("http://192.168.1.65:8000/api/user/logout/");
await removeToken();
return await response.json();
} catch (error) {
console.log(error);
throw error;
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论