【问题标题】:react native : there is way to use axios.put?反应原生:有办法使用 axios.put 吗?
【发布时间】:2020-03-31 12:13:05
【问题描述】:

在我的代码中,我尝试使用 axios 进行“放置”,但我不确定这样做的方式。 我想知道使用put 的最佳方式是什么。 如您所见,我使用componentdidmount 来触发putData() 函数。

export default class WaterQualitySamplesScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }


  // //post//////////////////////////////////
    putData = () => {
        const axios = require('axios')

        axios.put('https://harigotphat1.mekorot.co.il/m200_orderapprovehub/api/Installation?Platform=fcm&InstallationId=o-ritzhak&Handle=ExponentPushToken[JtL6KhGx8JxPeF3rO005WY]',
        { headers: {
          Authorization: 'Bearer ' + "my token"}
        })
            .then(function (response) {
                console.log(response);
            })
    }
    // ///////////////////////////////////

  registerForPushNotificationsAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
    if (status !== "granted") {
      alert("No notification permissions!");
      return;
    }

    try {
      // Get the token that identifies this device
      let token = await Notifications.getExpoPushTokenAsync();
      console.log("this is my token:", token);

      firebase
        .database()
        .ref("users/" + "/push_token")
        .set(token);
    } catch (error) {
      console.log(error);
    }
  };

  //////////////

  async componentDidMount() {
    this.currentUser = await firebase.auth().currentUser;
    await this.registerForPushNotificationsAsync();

    this.putData();
  }

  render() {
    return (
      <View style={styles.screen}>
        <TouchableOpacity
          onPress={() => {
            this.props.navigation.navigate({ routeName: "PLACES" });
          }}
          style={styles.button}
        >
          <Text style={styles.textButton}>TODO</Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            this.props.navigation.navigate({ routeName: "  " });
          }}
          style={styles.button}
        >
          <Text style={styles.textButton}>SAID</Text>
        </TouchableOpacity>
        <View style={styles.InfoTableBottomMainContainer}>
          <View style={styles.InfoTableBottomView}></View>
        </View>
      </View>
    );
  }
}

【问题讨论】:

  • 那么你的axios put到底有什么问题呢? axios put 应该是这样工作的,你确定你的后端服务器和 put one 配合得很好吗?
  • 我需要知道我的 "azure token" 才能在 "putData ()" 中使用它。这是我使用的 thr 库的链接:link 我如何从那里获取我的令牌?

标签: javascript reactjs react-native expo


【解决方案1】:
export const axiosPutReq = (url, data, authenticationId) => {
  return new Promise((resolve, reject) => {
    axios({
      method: "put",
      url,
      data,
      headers: {
        Authorization: "Bearer " + authenticationId,
        "Content-Type": "application/json",
        Accept: "application/json"
      }
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error);
      });
  });
};

【讨论】:

    【解决方案2】:

    我的代码sn-p:

      const authFetch = async (data) => {
      var header = {
        Accept: 'application/json',
        Authorization: 'authToken',
        //  access_token: data.data.token,
        'Content-Type': 'application/json',
      };
      0;
      //
      await AsyncStorage.getItem('accessToken').then((resp) => {
        header['accesstoken'] = resp;
      });
      //console.log(header)
    
      if (data.method == 'POST' || data.method == 'PUT') {
        return fetch(`${data.url}`, {
          method: data.method,
          headers: header,
          body: JSON.stringify(data.data),
        });
      } else {
        return fetch(`${data.url}`, {
          method: data.method,
          headers: header,
        });
      }
    };
    export default authFetch;
    

    像这样使用这个 authFetch 方法:

      export function yourFunctionName(data) {
      console.log(JSON.stringify(data));
      return new Promise((success, failure) => {
        authFetch({
          url: `${baseUrl}endpoint`,
          data: data,
          method: 'PUT',
        })
          .then((res) => {
            res.json().then((result) => {
              success(result);
            });
          })
          .catch((err) => {
            failure(err);
          });
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多