【问题标题】:POST data to php file via reactjs axios通过 reactjs axios 将数据发布到 php 文件
【发布时间】:2020-04-18 04:39:44
【问题描述】:

我正在尝试将数据发布到相对于 .js 文件高两个文件级别的 php 文件。我是 reactjs 新手,对 axios 并不完全熟悉,所以请耐心等待。

ReactJS 代码

onSubmit=(e)=>{
    e.preventDefault();
    alert(this.state.username);
    axios.post('../../connections/submit.php',{
      username:this.state.username
    }).then(res=>{
      console.log(res);
    }).catch(error=>{
      console.log(error);
    });
  };

有问题的 PHP 文件:

if(isset($_POST) && !empty($_POST)){
    $data = json_decode(file_get_contents("php://input"), true);
    $username = $data['username'];
    print_r($username);
    $conn=mysqli_connect("localhost","root","","jwt_test");
    $sqlOrder="INSERT INTO user(u_id,username) VALUES(NULL,'$username')";
    $conn->query($sqlOrder);
    $conn->close;
};

这是发布数据的正确方式吗?我收到一个 404 错误代码,说明它找不到我的文件。

我的文件结构是这样的:

-connections
    -submit.php
-src
    -components
        -submit.js

如果有帮助,我在 submit.js 文件中而不是在 App.js 文件中导入了 axios。 任何建议将不胜感激。感谢阅读。

【问题讨论】:

  • axios.post('../../connections/submit.php') 我认为这行不通.. 试试“localhost/yourproject/connections/submit.php
  • @Viduranga,对于本地主机,我是否这样做localhost:3000?还是只是本地主机:3000?这是新路径:localhost:3000/test/connections/submit.php
  • 不不。要工作 php 文件,您需要将它托管在服务器上 .. 像 apache 一样。 nginx ..如果你在本地机器上测试这个安装xampp(它包括php + apache)然后把你的php文件放在那个服务器中..然后启动服务器(通常它像localhost一样开始)这样托管文件的url应该添加到axios .post();
  • 好的,现在唯一的问题是跨域错误。我想我可以应付。谢谢@Viduranga
  • @Dharman,更新了代码以反映这一点。感谢您的提醒。

标签: reactjs axios


【解决方案1】:

我已经开始工作了。对于 reactjs 文件,代码如下:

onSubmit=(e)=>{
    e.preventDefault();
    alert(this.state.username);
    //!!! need to stringify the payload before sending it to phpmyadmin.
    var payload = {
      username:this.state.username
    };
    axios.post('http://localhost/connections/submit.php',
    JSON.stringify(payload)).then(res=>{
      console.log(res);
    }).catch(error=>{
      console.log(error);
    });
  };

接收PHP文件:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");

if(isset($_POST) && !empty($_POST)){
    $data = json_decode(file_get_contents("php://input"), true);
    $username = $data['username'];
    $conn=mysqli_connect("localhost","root","","jwt_test");
    $stmt = $conn->prepare("INSERT INTO user(u_id,username) VALUES(NULL,?)");
    $stmt->bind_param('s',$username);
    $stmt->execute();
    $conn->close;
};

需要的是 PHP 文件中的两个标头,将负载编码为 JSON 并使用另一个服务器接收负载,在本例中,使用了 XAMPP。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2023-02-04
    • 2014-11-16
    相关资源
    最近更新 更多