如何将访问令牌从 API 存储到 asyncstorage



异步存储错误:未定义访问令牌

如何定义访问令牌我正在使用 PHP 作为后端 API,并使用访问令牌进行注册以存储在异步存储中

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);
      });
  }
}
如何

调用访问令牌以在函数中定义。如何弄清楚这一点如果使用 await 函数访问令牌,则它显示错误 await 不是函数

    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);
          });
      }
    }

最新更新