【问题标题】:Api call to post data not working with either fetch or axios用于发布数据的 API 调用不适用于 fetch 或 axios
【发布时间】:2020-11-19 13:04:22
【问题描述】:

我正在尝试在反应中发布注册请求的数据。我试图检查数据是否传递给 api,但它都是空的。这是我注册 api 的 php 代码。

<?php 
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
header("Content-type:application/json");

$username = isset($_GET['username']) ? $_GET['username'] : '';
$password = isset($_GET['password']) ? $_GET['password'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
$name = isset($_GET['name']) ? $_GET['name'] : '';

$jsonResponse = array();

$con = mysqli_connect("localhost", "root", "", "example");
if(!$con) {
    $jsonResponse = array("code" => "601", "message" => "Unexpected Error, Please try again.");
} else {
    $phone_len = strlen($username);
    if($phone_len != 10 ){
        echo($username);
        $jsonResponse = array("code" => "605", "message" => "Mobile number is not 10 Digit","username"=>"$username","password"=>"$password");
    } else{...}

这是我使用 fetch 发布代码的代码。

const requestOption ={
                    method:'POST',
                    header:{'Content-Type':'application/json'},
                    body:JSON.stringify({username:phone,name,password})
                };
                fetch('http://localhost:8080/example/signup.php',requestOption)
                .then(res=>res.json())
                .then(data=>{console.log(data);JSON.stringify(data)})
                .catch(err=>{
                    console.log(err)
                })

我也尝试使用 axios 发布数据。

axios.post('http://localhost:8080/example/signup.php', {username:phone,name:name,password:password})
                    .then(res => {
                        console.log(res)
                        console.log(res.data)
                    })
                    .catch(err => {
                        console.log(err)
                    });

【问题讨论】:

  • 您是否在控制台中收到任何 javascript 错误?
  • 我在控制台中没有收到任何 javascript 错误

标签: php reactjs api post fetch


【解决方案1】:

您正在使用 POST 请求将数据发送到 php 脚本。这意味着您应该查看 $_POST 变量而不是 $_GET

$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';

【讨论】:

  • 但是当数据通过邮递员时,同样的代码工作正常。
  • $_POST 超全局中有什么东西吗?
  • $_POST 中什么都没有。
猜你喜欢
  • 2018-06-22
  • 2021-08-07
  • 2019-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2021-01-16
  • 2017-02-02
  • 1970-01-01
相关资源
最近更新 更多