如何在React Native中使用post方法?

时间:2018-09-02 08:56:17

标签: reactjs react-native react-native-android

     constructor(props) {
        super(props);
        this.state = {text: this.props.navigation.state.params.text,
    name:this.props.navigation.state.params.name};
      }

    manage = () => {

    Alert.alert('done')
      Actions.reset('mainScreen');

    fetch("http://ip/api/confirm", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({

        name: this.props.navigation.state.params.name,
        text:this.props.navigation.state.params.text
      })
    })
    .then(response => response.json())

      .catch(error => {
        console.error(error);
      });

    }

我想这样做

当我按下按钮时进入管理功能 并将文本和名称发布到我的api上,我不知道如何传递它们

  

它给我这个错误:    网络请求失败

请帮忙

2 个答案:

答案 0 :(得分:0)

我建议您使用axios发出网络请求。

安装:

npm i -S axios

执行POST请求:

import axios from 'axios';

axios({
    url: 'http://ip/api/confirm',
    method: 'post',
    data: {
      name: this.props.navigation.state.params.name,
      text: this.props.navigation.state.params.text,
    },
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

答案 1 :(得分:0)

 var resp = await manage(this.props.session.userId,this.props.session.ApiKey,"hi","hello");
      if (resp.status == 200){
         var respBody = await resp.json();
        console.log('Fetch Todo response '+respBody); 
      }

API在单独的文件中

export async function manage(userId,ApiKey,query,query1) {

  var url ="http://www.example.com/getdata";

  const params = {
    search:query,
    searches:query1
  };


  var formBody = [];
for (const property in params) {
const encodedKey = encodeURIComponent(property);
const encodedValue = encodeURIComponent(params[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}

formBody = formBody.join("&");


const requestOptions = {
'method': 'POST',
'headers': {
   'Content-Type': 'application/x-www-form-urlencoded'
  // 'Content-Type': 'application/json'
},
'body': formBody

};

  requestOptions.headers["userid"] = userId
  requestOptions.headers["apikey"] = ApiKey

  try {
    var resp = await fetch(url, requestOptions);
    return resp;
  }
  catch (err) {
    console.log("Request Failed: " + err);
    return err;
  }
}