AsyncStorage错误:未定义访问令牌
如何定义accesstoken我正在使用php作为后端api并向accesstoken进行注册以存储在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);
});
}
}
如何调用accesstoken在函数中定义。如何弄清楚 如果使用await函数访问令牌,则表明错误await不是函数
答案 0 :(得分:1)
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);
});
}
}