无法获取令牌-使用异步存储方法-React Native(Expo)

时间:2019-03-07 16:30:08

标签: react-native expo

我正在处理反馈表,登录到随机用户帐户后无法从服务器获取令牌。这是我的代码:

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>

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

据我了解,您没有保存令牌。您需要先保存它,然后才能检索它。如果您可以在接收令牌的地方共享代码,这将很有帮助,但这是将某些内容保存到AsyncStorage的常规语法。另外,请确保调用getToken()函数。

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