简体   繁体   中英

how to use headers in fetch on React-Native or Expo

I want to communicate with the server.

In order to communicate with the server, two items must be added to headers .

Note: The key value written is not the actual key value.

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

The code I tried to communicate with:

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

But this is not working

Error:, [TypeError: Network request failed]

How can I communicate with the server? Is there another way?

thank you in advance

It was a mistake in my address,

but the server receiving the data says the data is null. How can we solve the problem?

I solved it by using formdata .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM