React Native Fetch:Post 正在发送但未在 PHP 文件中收到

React Native Fetch: Post being sent but not received in PHP file

我已经设置了一个 php 文件来根据发送的内容 post 改变查询,我已经用一个表单测试了它并且它成功运行。

<?php

$pdo = new PDO("mysql:host=localhost;dbname=...","...","...",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if(isset($_POST['country'])){

    $query = stripslashes("SELECT A.id, A.supplier_id, A.pickup_date, A.dropoff_date, A.rate, A.days_allowed, A.fuel_allowed, A.location_from, A.location_to, A.dropoff_office_id,      A.pickup_office_id, A.vehicle_type_id, B.city AS location_from_city, C.city AS location_to_city, D.vehicle_type,D.transmission FROM _relocation_deals A JOIN _airport_codes_lookup B ON A.location_from = B.code JOIN _airport_codes_lookup C ON A.location_to = C.code JOIN _vehicle_types D ON A.vehicle_type_id = D.id WHERE B.country = '".$_POST['country']."' AND A.active = 1 AND A.status = 1 ORDER BY A.pickup_date ASC");

$data = array();

try
{
    $sql = $query;
    $result = array();
    $stmt = $pdo->prepare($sql);
        $stmt->execute();   
    while($result = $stmt->fetch()){
        $data[] = $result;
    } 
}
    catch (PDOException $e)
{
    echo $e->getMessage();
}

    echo json_encode($data);
}else{
    $arr = array('error' => 'no post sent');
    echo json_encode($arr);  
}

?>

我在 React Native 中使用 post 获取此文件。

fetch(REQUEST_URL, {
  method: 'POST',
  headers: {
    'Accept': 'text/html',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: JSON.stringify({
    country: "New Zealand"
  })
})
  .then((response) => response.json())
  .then((responseData) => {
    console.log(responseData);
  })
  .catch((error) => {
    console.error(error);
});

我可以在我的网络检查器中看到发送的数据是 {"country","New Zealand"} 但我得到的响应是 {"error", "no post sent"}。为什么我的 PHP 文档没有收到这个 post 是有原因的?谢谢

您需要对请求正文进行编码 as URI 而不是 JSON:

body: 'country=' + encodeURIComponent('New Zealand'),

或者您可以从 php://input 中读取 POST 参数并从 JSON 手动解码它们。

此外,您的 PHP 代码 非常 vulnerable. You should never insert parameters from HTTP-request and other untrusted data in the SQL query string. stripslashes() is not a way to escape special characters of SQL. You already use PDO and prepared statements, so just bind parameters through appropriate methods such as bindValue()