首页 > 解决方案 > php文件未从axios post请求接收数据

问题描述

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

标签: phpreactjsaxios

解决方案


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

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

它应该工作。

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


推荐阅读