【问题标题】:php file not receiving data from axios post requestphp文件未从axios post请求接收数据
【发布时间】: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。谢谢

标签: php reactjs axios


【解决方案1】:

如果您通过 ajax 以正确的 JSON 格式将数据发送到服务器,它应该已经在您的全局 $_POST 变量中。您可以通过使用var_dump($_POST) 查看其内容来确保您正在获取数据。如果它包含您的数据,则无需从输入流中读取值,对其进行解码然后覆盖您的全局变量,您可以使用以下行:

$msg = $_POST['name'] . $_POST['email'] . $_POST['organisation'] . $_POST['contactno'] . $_POST['message'];

它应该可以工作。

此外,您可以为每个参数使用filter_input(INPUT_POST, "variable") 而不是$_POST["variable"],以确保它们已设置并防止错误。

【讨论】:

  • “如果您通过 ajax 以正确的 JSON 格式将数据发送到服务器,它应该已经在您的全局 $_POST 变量中。” - 不,它不应该。 PHP 只为 Content-Type application/x-www-form-urlencoded 或 multipart/form-data 的请求填充 $_POST。
  • 您可以使用控制台[链接] (tulisuites.com/#/contactus)在此页面上查看 axios json 结果
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 2021-10-21
  • 2021-08-28
  • 2018-07-23
  • 2010-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-05-08
相关资源
最近更新 更多