Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

php - trying to connect an api with react native

I am trying to connect an api using react-native. I need to use php, there is no other possibility because I will connect with a system already made and it is in php. The database is postgresql

Php code:

<?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";
?>

React native code:

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

When I try to register, it gives an error. "Network request failed"

Pgadmin is running

question from:https://stackoverflow.com/questions/65943582/trying-to-connect-an-api-with-react-native

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...