【发布时间】:2019-09-05 07:00:04
【问题描述】:
php 文件未从axios 发布请求接收数据。表单提交后显示未定义的错误。我在 react js 中创建了表单。所有字段和状态变量都正确显示。
axios({
method: 'post',
url: 'http://tulisuites.com/form.php',
headers: { 'content-type': 'application/json' },
data:JSON.stringify(this.state)
})
.then(result => {
this.setState({
mailSent: result.data.sent
});
console.dir(this.state);
})
.catch(error => this.setState({ error: error.message }));
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Content-Type: application/json");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$subject = "Enquiry form";
$to = "sample@domainname.com";
// data
$msg = $_POST['name'] . $_POST['email'] . $_POST['organisation'] . $_POST['contactno'] . $_POST['message'];
// Headers
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=UTF-8\r\n";
$headers.= "From: <admin@tulisuites.com>";
mail($to, $subject, $msg, $headers);
?>
【问题讨论】:
-
由于
$_POST是一个超全局变量,你应该可以直接从$_POST接收你的数据,或者使用$_REQUEST获取所有方法。在我看来,没有必要使用file_get_contents("php://input");。 -
@JakobKronsteiner PHP 仅填充 $_POST,如果请求的 Content-Type 是
application/x-www-form-urlencoded或multipart/form-data。这里是application/json,所以需要直接从原始输入流中读取。 -
那么您发送的 JSON 实际是什么样的?
-
@misorude 好的,感谢您的更新。以前没有这样的情况。所以我们需要查看之前询问的 json-data。谢谢