React Native无法从本地主机获取响应

时间:2020-04-27 20:43:09

标签: react-native

我正在与React Native一起学习, 但我无法正确回应 我的提取代码是:

try {
     let response = fetch(
      "http://192.168.1.106/little_api/index.php",
      {
        method: "POST",
        headers: {
         "Accept": "application/json",
         "Content-Type": "application/json"
        },
       body: JSON.stringify(data)
     }
    );


     console.log(response);

响应为:

enter image description here

尝试邮递员时从api获得的api响应:

enter image description here

我的php API是: enter image description here

但是我的调试器控制台响应为enter image description here

3 个答案:

答案 0 :(得分:2)

fetch()函数返回一个诺言,因此您应使用以下两种方法之一来解决此诺言:

1 /使用.then()

fetch(
      "http://192.168.1.106/little_api/index.php",
      {
        method: "POST",
        headers: {
         "Accept": "application/json",
         "Content-Type": "application/json"
        },
       body: JSON.stringify(data)
     }
   ).then(response => {
      console.log(response); //<- your response here
   }).catch(error => {
      console.log(error); //<-catch error
 });

2 /使用async/await语法:您应在调用fetch的函数上添加async关键字

async getResponse(){
try {
   let response = fetch(
      "http://192.168.1.106/little_api/index.php",
      {
        method: "POST",
        headers: {
         "Accept": "application/json",
         "Content-Type": "application/json"
        },
       body: JSON.stringify(data)
     }
    );
   console.log(response); //<- your response here
  } catch(e){
  console.log(e);<-catch error
  }
}

答案 1 :(得分:1)

您可以使用formdata发送它:

let formData = new FormData();
formData.append('firstname', 'test');

如果这样做,则不必使用JSON.stringify:

fetch(
  "http://192.168.1.106/little_api/index.php",
  {
    method: "POST",
    headers: {
     "Accept": "application/json",
     "Content-Type": "application/json"
    },
   body: data
 }
 ...

答案 2 :(得分:0)

fetch是一个异步方法,这意味着它需要一个.then回调。立即从中获得的数据然后附加了一个json()方法,以便以可读格式检索实际数据。

  fetch("http://192.168.1.106/little_api/index.php", {
    method: "POST",
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
 }).then(response => response.json())
   .then(data => {
     console.log(data) // this should return your data
   })
   .catch(err => console.log(err))

正如Mahdi N在回答中所说,您可以使用async/await语法来检索数据,而无需嵌套的回调。