【发布时间】:2021-05-02 17:31:16
【问题描述】:
我正在尝试使用 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 正在运行
【问题讨论】:
-
您的开发服务器只是没有端口号的本地主机?即
http://localhost:8000 -
是的,就是这样
标签: php postgresql react-native api