-1

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?

  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Feb 19 '22 at 21:39

1 Answers1

0

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I've installed XAMPP and in the control pannel i've found some errors, thanks for the hint. – Michelangelo Feb 20 '22 at 07:32
  • I think I solved all the problems related to XAMPP but the problem is still happening. I changed the URL of axios in "http://localhost:3000/src/api/addPeople.php" and I get this error: Error: Request failed with status code 404 at createError (createError.js:16:1) at settle (settle.js:17:1) at XMLHttpRequest.onloadend (xhr.js:66:1) – Michelangelo Feb 20 '22 at 11:06
  • 1
    `3000` is the traditional port used by Express and the React dev server. You need to use a URL that points to the Apache server that is part of XAMPP (typically the default port so removing `:3000` would be a good start). Then you need to make sure that `/src/api/addPeople.php` actually maps from the DocumentRoot of the Apache server (because that looks like a path in your Node.js project) – Quentin Feb 20 '22 at 12:29
  • Watching XAMPP, my Apache server runs on 80 or 443, so i decided to run the react app on 80 but it tells me to change the port (because it's occupied by XAMPP) tu run it, and if i decide to say no it simply doesn't run the app. The react app is placed in is a path like this "xampp>htdocs>test>appFolder" and it's should be correct. – Michelangelo Feb 20 '22 at 17:19
  • 1
    You can't run the react's HTTP server and Apache's HTTP server on the same port. If you want Apache to serve the React application then you need to run the build script and put the production rules under Apache's web root. That's a real pain for development so you should leave that for production. Just put your API under Apache (and, as I said in the answer, make it CORS aware). – Quentin Feb 20 '22 at 17:20
  • I've checked the httpd.conf file to find the Document root of apache and it is "xampp>htdocs" so I've placed there addPeople.php and with the axios route "/addPeople.php" i've tried the app. Same error. I can't really find what i am doing wrong, I don't think the problem is the code, because i've watched a lot examples online and they do similar things that i do. – Michelangelo Feb 20 '22 at 21:06
  • 1
    The route you pass to axios is relative to the HTML document, which is hosted on the server running on port `3000`. You need to use an absolute URL that points to the server running on port `80`. – Quentin Feb 20 '22 at 21:22
  • Thanks a lot, this morning i've finally connected the database and i've done my first post. – Michelangelo Feb 21 '22 at 08:48