I’m creating an app that must have a database in an online server.
On this server there this PHP Api:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$request_service = $_POST["service"];
$conn = getConnection();
$rows = array();
$query_result;
switch ($request_service) {
case "getTestOne":
$query_result = getTestOne($conn);
break;
case "getTestTwo":
$query_result = getTestTwo($conn);
break;
}
//echo $query_result;
echo parseResultToJson($query_result);
$conn->close();
function parseResultToJson($result) {
while($r = mysqli_fetch_assoc($result)) {
$returnRows[] = $r;
}
return json_encode($returnRows);
}
function getConnection() {
// the * are there for privacy, in the real code there are the real data
$servername = "******";
$username = "******";
$password = "******";
$database = "******";
$o_conn = new mysqli($servername, $username, $password, $database);
if ($o_conn -> connect_errno) {
echo "Failed to connect to MySQL: " . $o_conn -> connect_error;
exit();
}
return $o_conn;
}
function getTestOne($i_conn) {
$result = $i_conn->query("SELECT * FROM Test;");
return $result;
}
function getTestTwo($i_conn) {
$result = $i_conn->query("SELECT * FROM TestTwo;");
return $result;
}
?>
I try to send a POST request from my React Native app:
import { Component } from "react"
import { Button, Text, View } from "react-native";
export default class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
}
this.fetchData = this.fetchData.bind(this)
}
componentDidMount() {
}
fetchData() {
fetch("https://homey.altervista.org/testApi.php", {
method: "POST",
mode: "no-cors",
headers: {
"Accept": "application/json",
"Content-type": "application/json"
},
body: JSON.stringify({
service: "getTestOne"
})
})
.then((response) => console.log((response)))
.catch((error) => console.log("ERROR: " + error));
}
render() {
return (
<View>
<Button
title={"Fetch Data"}
style={{width: 300, height: 100}}
onPress={this.fetchData}
/>
</View>
)
}
}
but the response is:
{
"type": "default",
"status": 200,
"ok": true,
"statusText": "",
"headers": {
"map": {
"content-type": "text/html; charset=UTF-8",
"date": "Fri, 06 Oct 2023 09:10:07 GMT",
"server": "Apache",
"vary": "Accept-Encoding"
}
},
"url": "https://homey.altervista.org/testApi.php",
"bodyUsed": false,
"_bodyInit": {
"_data": {
"size": 4,
"offset": 0,
"blobId": "f8086baf-3a86-4b59-b07b-531a884f082d",
"__collector": {}
}
},
"_bodyBlob": {
"_data": {
"size": 4,
"offset": 0,
"blobId": "f8086baf-3a86-4b59-b07b-531a884f082d",
"__collector": {}
}
}
}
Using Postman it works perfectly:
I tried to convert the response using response.json() or response.blob() but it doesn’t work.