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
Solution 1:
You should first figure out if the problem lies with the server or the application. You can do so using Postman (https://www.postman.com/). Send your request using Postman and see if everything is returned correctly. If Postman cannot connect either, the problem lies with your server and you should further investigate into that direction. Otherwise, the problem lies with your application and there could be multiple reasons for that.
If you're using IOS to run the application, the Network Request Failed
error is likely caused by fetching a HTTP resource as this is disallowed by default on 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
file (see here https://stackoverflow.com/a/38427829/17922074 for more info on that).
Some other points related to your code:
You should definitely look into prepared statements for your database interaction (https://www.php.net/manual/de/function.pg-prepare.php). Because like this, your application will be vulnerable to SQL injection attacks (https://www.w3schools.com/sql/sql_injection.asp).
If you want to build larger applications, like this you'll need to copy the entire fetch()
call wherever you want to fetch data. A better option would be to create reusable service functions. I recently wrote a post on how to do this: https://schneider-lukas.com/blog/react-connect-rest-api.