API调用未接收到POST数据

时间:2018-09-02 07:42:12

标签: php json api post

我已经在PHP上构建了一个API。在发送POST请求时,POST URL中提供的变量没有被接收,并且输入数据集为空。提供的create.php中的以下数据变量为空。

如果我们在创建PHP文件中提供了硬编码数据,那么它工作正常。

下面是我的主要data.php文件代码。其中包含使用POST变量创建产品的功能。

<?php
class Data{
private $conn;
private $table_name = "data";
public $id;
public $email;
public $address;
public $lasttx;
public $created;
public function __construct($db){
$this->conn = $db;
}

function create(){
$query = "INSERT INTO " . $this->table_name . " SET email=:email, 
address=:address, lasttx=:lasttx, created=:created";

$stmt = $this->conn->prepare($query);

$this->email=htmlspecialchars(strip_tags($this->email));
$this->address=htmlspecialchars(strip_tags($this->address));
$this->lasttx=htmlspecialchars(strip_tags($this->lasttx));
$this->created=htmlspecialchars(strip_tags($this->created));

$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":address", $this->address);
$stmt->bindParam(":lasttx", $this->lasttx);
$stmt->bindParam(":created", $this->created);

if($stmt->execute()){
return true;
  }
return false;
}

下面是在API调用中被调用的create.php代码。该文件接收数据并在data.php中调用create函数

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow- 
Headers, Authorization, X-Requested-With");

include_once '../config/database.php';
include_once '../objects/data.php';

$database = new Database();
$db = $database->getConnection();

$data1 = new Data($db);

$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.

$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');

if($data1->create()) {
    echo '{';
        echo '"message": "Product was created."';
    echo '}';
}
else{
    echo '{';
        echo '"message": "Unable to create product."';
    echo '}';
}
?>

请告知。非常感谢。

1 个答案:

答案 0 :(得分:1)

u 正如您在评论中指出的那样,表单变量是通过URL提交的。在上面的脚本中,您尝试解析一个JSON对象,该对象是请求的有效负载。而且那不是这些参数所在的位置,因此您不会从那里获取任何数据。

要从PHP中的URL访问变量,您要做的就是从$_GET数组中获取它们。例如该电子邮件将在$_GET["email"]中。

所以这部分在这里:

$data = json_decode(file_get_contents("php://input"), true); // THIS VARIABLE is EMPTY while calling API.
$data1->email = $data["email"];
$data1->address = $data["address"];
$data1->lasttx = $data["lasttx"];
$data1->created = date('Y-m-d H:i:s');

将变为:

# $data = json_decode line goes away
$data1->email = $_GET["email"];
$data1->address = $_GET["address"];
$data1->lasttx = $_GET["lasttx"];
$data1->created = date('Y-m-d H:i:s');

希望这会有所帮助

Matthias