【问题标题】:React Native Fetch: Post being sent but not received in PHP fileReact Native Fetch:在PHP文件中发送但未收到的帖子
【发布时间】:2016-12-02 06:46:07
【问题描述】:

我已经设置了一个 php 文件来根据正在发送的帖子更改查询,我已经用一个表单对此进行了测试,它可以成功运行。

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

?>

我正在使用 fetch 在本机反应中发布到此文件。

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 文档没有收到这篇文章有什么原因吗?谢谢。

【问题讨论】:

    标签: php react-native fetch


    【解决方案1】:

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

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

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

    另外,您的 PHP 代码非常 vulnerable。您永远不应该在 SQL 查询字符串中插入来自 HTTP 请求的参数和其他不受信任的数据。 stripslashes() 不是转义 SQL 特殊字符的方法。您已经使用 PDO 和prepared statements,因此只需通过bindValue()等适当的方法绑定参数即可。

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      相关资源
      最近更新 更多