无法获取令牌 - 使用异步存储方法 - 反应本机(博览会)



我正在处理反馈表格,并且在登录随机用户帐户后,我很难从服务器上获得令牌。这是我的代码:

getToken功能:

getToken = async () => {
    try {
      const value = await AsyncStorage.getItem("token");
      this.setState({ userToken: value });
    } catch (error) {
      console.log("Error retrieving data" + error);
    }
};

提交功能:

postFeedback(userToken, title, content, to_id, category) {
    fetch(
      "https://deployattendancemanagement.herokuapp.com/api/feedback/send",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        body: JSON.stringify({
          token: userToken,
          title: title,
          content: content,
          to_id: to_id,
          category: category
        })
      }
    )
      .then(response => response.json())
      .then(res => {
        if (typeof res.result != "success") {
          console.log(res.message);
          Alert.alert(
            "Oops !",
            "Something went wrong",
            [
              {
                text: "OK",
                onPress: () => console.log("Cancel Pressed"),
                style: "cancel"
              }
            ],
            { cancelable: false }
          );
        } else {
          console.log("success");
          Alert.alert(
            "Yay !",
            "Something went right",
            [
              {
                text: "OK",
                onPress: () => console.log("Send feedback"),
                style: "cancel"
              }
            ],
            { cancelable: false }
          );
        }
      })
      .catch(error => {
        console.error(error);
      });
  }

按钮:

<Button
   full
   onPress={() =>
     this.postFeedback(
       this.state.userToken,
       this.state.title,
       this.state.content,
       this.state.to_id,
       this.state.category
     )
   }
>
  <Text>SUBMIT</Text>
</Button>

但是在按下按钮后,标题和内容没有发送,它给了我这个错误:不提供令牌。请帮忙,我是React-Native编程的新手。

您尚未在代码中调用getToken()函数。那将是这里的问题。

据我了解,您没有保存令牌。您需要保存它,然后才能检索它。如果您可以共享收到令牌的代码,但这是将某些内容保存到Asyncstorage的一般语法,这将是有帮助的。还要确保调用getToken()函数。

saveToken = async () => {
 let token = 'something';
 await AsyncStorage.setItem('key', token); 
};

最新更新