繁体   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