【问题标题】:how to use headers in fetch on React-Native or Expo如何在 React-Native 或 Expo 的 fetch 中使用标头
【发布时间】:2019-05-14 03:31:41
【问题描述】:

我想和服务器通信。

为了与服务器通信,必须在headers 中添加两项。

注意:写入的键值不是实际的键值。

  • api_key: "abcdegeg123456842536ebebeb1yeyju",
  • game_key: "abcdegeg123456842536ebebeb1yeyju"

我尝试与之通信的代码:

checkNickName = async () => {
    fetch("http://192.168.0.44:11000/v1/point/auth/change_nickname", {
      method: "POST",
      body: JSON.stringify({
        wallet_address: "0f8751828af26816ef996c37e611b945304a6e99",
        new_nickname: this.state.nickname
      }),
      headers: {
        // "Content-Type": "application/json"
        api_key: "abcdegeg123456842536ebebeb1yeyju",
        game_key: "abcdegeg123456842536ebebeb1yeyju"
      }
    })
      .then(res => res.json())
      .then(response => {
        console.log("response:" + response);
        console.log(response.resultCode);
        if (response.resultCode == "S000") {
          Alert.alert("info","scess");
        } else alert(response.result);
      })
      //console.log("Success:", JSON.stringify(response))
      .catch(error => console.error("Error:", error));
  };

但这不起作用

错误:,[TypeError:网络请求失败]

如何与服务器通信?还有其他方法吗?

提前谢谢你

【问题讨论】:

  • 你是在 iOS 还是 Android 中测试网络通话?
  • @QuokMoon 现在正常了,但是从服务端接收数据时为null。

标签: javascript ajax react-native fetch expo


【解决方案1】:

我的地址写错了,

但是接收数据的服务器说数据是空的。我们该如何解决这个问题?

我使用formdata解决了这个问题。

使用Page.js

 async checkNickName() {
    let formdata = new FormData();
    formdata.append(
      "wallet_address",
      "gBx0f8751828af26816ef996c37e611b945304a6e99"
    );
    formdata.append("new_nickname", this.state.nickname);
    fetch("http://192.168.0.26:11000/v1/point/auth/change_nickname", {
      method: "POST",
      body: formdata,
      headers: {
        "Content-Type": "multipart/form-data",
        api_key: "5b95576338b1eb1c53a1ae3f904dc7c5",
        game_key: "bf61b73dd871c2973188706d813002c2"
      }
    })
      .then(res => res.json())
      .then(response => {
        console.log(response);
        console.log(response.resultCode);
        if (response.resultCode == "S002") {
          AsyncStorage.setItem("gbrickobj", this.state.gbrickobj);
          AsyncStorage.setItem("nickname", this.state.nickname);
          this.props.navigation.navigate("RegisterSecurity");
        } else if (response.resultCode == "S001") {
          this.setState({
            checknick: "this nickname already use nickname."
          });
        } else {
          Alert.alert("info", "check address.");
        }
      })
      .catch(error => console.error("Error:", error));
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 2018-09-16
    • 2021-09-18
    • 2020-07-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    相关资源
    最近更新 更多