簡體   English   中英

嘗試將 api 與本機反應連接

[英]trying to connect an api with react native

我正在嘗試使用 react-native 連接 api。 我需要使用 php,沒有其他可能性,因為我將連接一個已經制作好的系統,它位於 php 中。 數據庫為 postgresql

Php 代碼:

<?php
  $connect = pg_connect ("host=localhost port=5432 dbname=teste user=postgres password=123");

  $json = file_get_contents('php://input');

  $obj = json_encode($json, true);

  $name = $obj['name'];

  $insert = "INSERT INTO usuario (id, name) VALUES (3, '$name')";
  $query = pg_query($connect, $insert);

  if($query){
      echo json_encode('Registrado');
  }else{
      echo json_encode("Falha");
  }
  // include "connect.php";
?>

反應本機代碼:

export default function App() {

  const [name, setName] = useState('');

  function register() {
    fetch('http://localhost/postgresql/', {
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-type': 'application/json'
      },
      body:JSON.stringify({
        name: name,
      })
    })
    .then((response) => response.json())
      .then((responseJson) => {
        alert(responseJson)
      })
      .catch((error) => {
        alert(error)
      })
  }

  return (
    <View>
      <Text>
        Bem vindo ao meu App!
      </Text>

      <TextInput 
        placeholder="Enter name"
        onChangeText={name => setName(name)} 
        value={name}
      />

      <Button 
        title="Registrar"
        onPress={register}
      />
    </View>
  )
}

當我嘗試注冊時,它給出了一個錯誤。 “網絡請求失敗”

pgadmin 正在運行

您應該首先確定問題出在服務器還是應用程序上。 您可以使用 Postman ( https://www.postman.com/ ) 執行此操作。 使用 Postman 發送您的請求,看看是否所有內容都正確返回。 如果 Postman 也無法連接,則問題出在您的服務器上,您應該進一步調查該方向。 否則,問題出在您的應用程序上,可能有多種原因。

如果您使用 IOS 運行應用程序,則Network Request Failed錯誤可能是由獲取 HTTP 資源引起的,因為默認情況下 IOS 不允許這樣做。 You can either add SSL to your server (how to do this for the Apache web server: https://httpd.apache.org/docs/2.4/ssl/ssl_howto.html ) and fetch via HTTPS, or add an entry to your info.plist文件(有關更多信息,請參見此處https://stackoverflow.com/a/38427829/17922074 )。

與您的代碼相關的其他一些要點:

您絕對應該查看為您的數據庫交互准備的語句( https://www.php.net/manual/de/function.pg-prepare.php )。 因為這樣,您的應用程序將容易受到 SQL 注入攻擊( https://www.w3schools.com/sql/sql_injection.asp )。

如果您想構建更大的應用程序,像這樣,您需要將整個fetch()調用復制到您想要獲取數據的任何位置。 更好的選擇是創建可重用的服務功能。 我最近寫了一篇關於如何做到這一點的帖子: https://schneider-lukas.com/blog/react-connect-rest-api

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM