php api调用另一个php api-正文丢失

时间:2019-06-29 13:58:32

标签: php api curl

我创建了一个php API,它也需要调用我也创建的另一个API。我已经用Postman测试了第二个,它给出了预期的结果。但是当我测试第一个api时,第二个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"

//第二个必须调用第一个的

// 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"

1 个答案:

答案 0 :(得分:0)

您的数据应位于$response

使用

进行测试
echo $response;

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