【发布时间】: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,更新了代码以反映这一点。感谢您的提醒。