使用 Axios post 请求和 PHP 的问题

Problems using Axios post request and PHP

我正在尝试使用 axios 从 React 向 PHP 文件发送 post 请求。处理按钮提交数据的函数是这样的:

    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);
    });  
    
}

在 addPeople.php 文件中我有这个:

$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();
    }

从反应中我没有得到任何错误,这意味着我没有语法错误,但我得到错误:

Cannot POST /src/api/addPeople.php

我还有第二个小问题。我已经尽可能地简化了 .php 文件来查找错误,但第一个想法是创建一个 php class 带有一些函数来处理请求,我是想在 axios post 方法中有一个 URL 这样的“path/to/phpFile/functionName”,对吗?

您需要在可以执行 PHP.

的网络服务器上托管您的 PHP 程序

错误消息表明您正在尝试将其托管在 Webpack 开发服务器(适用于托管 React 应用程序和属于其中的任何 static 文件)或 Express.js.

选择一个支持 PHP 的服务器(比如它的 built-in server or a suitably configured Apache HTTPD), add (需要包括 pre-flight 支持),并使用 absolute URL 在您的参数中传递给 axios.