首页 > 解决方案 > php api调用另一个php api-body丢失

问题描述

我创建了一个 php api,它需要调用我创建的另一个 api。我已经使用 Postman 测试了第二个,它给出了预期的结果。但是当我测试第一个时,第二个 api 没有收到正文数据。似乎它已经丢失了。

我下面的代码有问题吗?

非常感谢您的帮助。

//第一个需要调用的api(http://mylocalsite.com/user/create

// required headers
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");

// get posted data
$data = json_decode(file_get_contents("php://input"));

// display data
var_dump($data);

// Displayed result
"NULL\n"

//第二个需要调用第一个的api

// required headers
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");

// get posted data
$data = json_decode(file_get_contents("php://input"));

$url = "http://mylocalsite.com/user/create";
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_POST, true);
curl_setopt($client, CURLOPT_POSTFIELDS, $userData);
curl_setopt($client, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($client);
curl_close($client);

发送的数据

{
    "username" : "anonymous_api",
    "password" : "secret123!",
    "firstname" : "anonymous_api",
    "lastname" : "anonymous_api",
    "email" : "anonymous_api@bookingpro.com",
    "role" : "USER"
}

预期数据

{
    "username" : "anonymous_api",
    "password" : "secret123!",
    "firstname" : "anonymous_api",
    "lastname" : "anonymous_api",
    "email" : "anonymous_api@bookingpro.com",
    "role" : "USER"
}

实际数据

"NULL\n"

标签: phpapicurl

解决方案


你的数据应该在$response

通过使用测试它

echo $response;

$data在第二个脚本中没有用。


推荐阅读