php - 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"
解决方案
你的数据应该在$response
通过使用测试它
echo $response;
您$data
在第二个脚本中没有用。
推荐阅读
- r - R Shiny 根据 Userinput 动态添加 textinput 并打印 ui 输出
- algorithm - 在 3D 边界框中以最佳方式拟合其他球体之间的球体的算法?
- reactjs - 使用模拟函数测试 React 存储
- sockets - 这段代码中的权重在哪里更新?
- r - 使用非标准评估按多列排序
- html - 灯箱的奇怪行为
- json - 如何修复convertapi中的“状态=内部服务器错误,状态代码=500”错误,以便在顶点中合并pdf?
- kubernetes - HPA labelSelector 不过滤外部指标
- php - Htaccess 将查询字符串作为目录解释为脚本
- java - 在android studio中使用线程崩溃Java apk