I am trying from react, using axios, to send a post request to a PHP file. The function that handles the button to submit the data is this:
function handleAddPeople(event){
const name = nameRef.current.value;
const surname = surnameRef.current.value;
const age = ageRef.current.value;
axios({
method: 'post',
url: 'src/api/addPeople.php',
data: {
name: name,
surname: surname,
age: age
}
}).then(function(response){
console.log(response);
}).catch(function (error) {
console.log(error);
});
}
And in the addPeople.php file i have this:
$con = mysqli_connect($host, $user, $password,$dbname);
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$_POST = json_decode(file_get_contents("php://input"),true);
echo $_POST['name'];
$name = $_POST["name"];
$email = $_POST["surname"];
$country = $_POST["age"];
$sql = "insert into tabella1 (name, surname, age) values ('$name', '$surname', '$age')";
$result = mysqli_query($con,$sql);
if (!$result) {
http_response_code(404);
die(mysqli_error($con));
} else {
$con->close();
}
From react i get no errors, meaning i have no syntax errors, but i get the error:
Cannot POST /src/api/addPeople.php
I have a second little problem. I've simplified as much as i can the .php file to find the error, but the first idea was to create a php class with some functions to handle the requests, i was thinking to have a URL like this "path/to/phpFile/functionName" in the axios post method, is it right?
CodePudding user response:
You need to host your PHP program on a web server that can execute PHP.
The error message suggests that you are trying to host it on either a Webpack development server (suitable for hosting React applications and any static files that are part of them) or Express.js.
Pick a server that supports PHP (such as its built-in server or a suitably configured Apache HTTPD), add CORS permissions (which will need to include pre-flight support), and use an absolute URL in your arguments passed to axios
.