【问题标题】:Axios and reactjs showing empty posted data at php backendAxios 和 react js 在 php 后端显示空的发布数据
【发布时间】:2020-03-27 01:49:47
【问题描述】:

我正在使用下面的 Axio Reactjs 代码将表单数据发布到 php 后端。

当我从 chrome 浏览器 console 检查 record.php 文件和 网络。它显示连接正常,但发布的数据为空。似乎 axios 没有将数据发送到 php 后端。

我在 SO 上尝试了一些解决方案,但无法使其正常工作。任何解决方法将不胜感激。

axios({
  method:'POST',
  url:'http://localhost/mydata/record.php',
  rec:{
    myParameter1: 'test',
    myParameter2: 'test2',

  }

}).then(res => {
        const data = res.data;
        this.setState({ data });
        console.log(data);
      })
.catch(err => { // log request error
        //this.setState({ error: false });
        console.error(err); 
      })

php 代码

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");

//header("Content-Type: application/json");


//check if file_get_contents is enabled
if( ini_get('allow_url_fopen') ) {
echo "enabled";
} else{
echo "not enabled";
}

$data = file_get_contents("php://input");
$request = json_decode($data);

print_r($request);
print_r($data);


?>

【问题讨论】:

  • 尝试将rec对象包裹在data键中,比如data : {rec: {...}}Docs

标签: php reactjs axios


【解决方案1】:

尝试在 axios 中删除数据段中的键 rec 或最好还是按照

的方式做一些事情
{
 rec: {
   myParameter1: 'test',
   myParameter2: 'test2',
 }
}

【讨论】:

    【解决方案2】:

    在 axios 文档中你可以找到数据标签:

    https://github.com/axios/axios#request-config

    // `data` is the data to be sent as the request body
      // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
      // When no `transformRequest` is set, must be of one of the following types:
      // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
      // - Browser only: FormData, File, Blob
      // - Node only: Stream, Buffer
      data: {
        firstName: 'Fred'
      },
    
      // syntax alternative to send data into the body
      // method post
      // only the value is sent, not the key
      data: 'Country=Brasil&City=Belo Horizonte',
    

    这就是你所需要的,在 axios 配置中没有 rec 属性

    【讨论】:

      猜你喜欢
      • 2019-02-12
      • 2021-07-11
      • 2023-02-04
      • 2019-09-15
      • 1970-01-01
      • 2022-09-26
      • 2020-06-11
      • 1970-01-01
      • 2019-03-14
      相关资源
      最近更新 更多