gpt4 book ai didi

react-native - 如何将访问 token 从 API 存储到异步存储

转载 作者:行者123 更新时间:2023-12-04 05:24:35 24 4
gpt4 key购买 nike

AsyncStorage 错误:未定义访问 token

如何定义访问 token 我使用 php 作为后端 api 并使用访问 token 进行注册以存储在 Asyncstorage 中

async storeToken(accesstoken) {
try {
await AsyncStorage.setItem(AccessToken, accesstoken);
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
userRegister = () =>{
const {username} = this.state;
const {password} = this.state;

if(username=="" || password==""){
alert("Please fill out all fields");
}
// else if (password!=cpassword) {
// alert("Passwords do not match.");
// }
else{
fetch('http://192.168.01.1/test/register.php', {
method: 'post',
header:{
'Accept': 'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
username: username,
password: password,

})
})
.then((response) => response.json())
.then((responseData) =>{
// how to define accesstoken
//this.storeToken('accessToken',JSON.stringify(results));
//if using in this then same error
this.storeToken('accesstoken',responseData.accesstoken)
if(responseData == 'User Registered Successfully'){
Alert.alert(
'Success',
'User Registered Successfully',
[
// {text:'ok', onPress: () => this.props.navigation.goBack() }
]
);
//this.props.navigation.goBack()
}else{
alert(responseJson);
}
})
.catch((error)=>{
console.log(error);
});
}
}

如何调用访问 token 在函数中定义。如何弄清楚这一点
如果使用 await 函数访问 token ,则会显示错误 await is not an function

最佳答案

    userRegister = () =>{
const {username, password } = this.state;

if(username=="" || password==""){
alert("Please fill out all fields");
}
// else if (password!=cpassword) {
// alert("Passwords do not match.");
// }
else{
fetch('http://192.168.01.1/test/register.php', {
method: 'post',
header:{
'Accept': 'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
username: username,
password: password,

})
})
.then((response) => {
// console the response here, if it's containing accesstoken then pass
it in your storeToken function like below
this.storeToken(response.accesstoken)
//after this do rest of your steps
})
.catch((error)=>{
console.log(error);
});
}
}

关于react-native - 如何将访问 token 从 API 存储到异步存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com