简体   繁体   中英

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

I've set up a php file to alter a query based on what post it is being sent, I've tested this with a form and it works successfully.

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

?>

I'm using fetch to post to this file in react native.

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

I can see in my network inspector that data sent is {"country","New Zealand"} but I get the response of {"error", "no post sent"}. Is there a reason why my PHP document isn't receiving this post? Thanks.

You need to encode request body as URI instead of JSON:

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

Or you can read POST parameters from php://input and decode them from JSON manually.

Also, your PHP code is very 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM