php - 如何在 php laravel 应用程序路由中处理从 API 端点(django 应用程序)返回的数据
问题描述
我有一个使用 Django 休息框架的 Django API 应用程序,它工作得很好。我有另一个应该使用 API 的 PHP laravel 应用程序。当我使用 curl 将数据发布到 API 端点时,会存储数据并返回一个对象。
我应该抓住这个对象并使用数据。但是,当我访问执行 post 请求的路由时,返回的对象会打印在页面上。
当我dd($data)
处理应该包含返回数据的变量时,我得到一个布尔值(当数据成功发布时为 true,如果出现问题则为 false)。
Route::get('test-create-client', function (){
try {
$data = ApiController::createClient('John D', '0711111111', '', 'Male', '1980'.'-'.date('m-d'));
} catch (Exception $exception) {
return $exception->getMessage();
}
dd($data); // I get a boolean from here
});
//从 ApiController 创建客户端
public static function createClient($name, $phone, $care_of, $gender, $date_of_birth)
{
$url = "client/clients/";
$client = '{
"name": "'.$name.'",
"telephone_number": "'.$phone.'",
"alternative_telephone_number": "'.$alt_phone.'",
"care_of": "'.$care_of.'",
"gender": "'.$gender.'",
"date_of_birth": "'.$date_of_birth.'",
}';
return ServicesApiController::RunCurlPostServices($url, $client);
}
//卷曲请求
public static function RunCurlPostServices($url, $json)
{
$ch = curl_init(env('SERVICES_API_URL').$url);
curl_setopt($ch, CURLOPT_POST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
我需要$data
API 端点返回的数据而不是布尔值。
解决方案
为了让 curlpost 返回 API 请求返回的内容,我必须设置CURLOPT_RETURNTRANSFER
为 true。由于某种原因,我错过了它。
所以将我的 curl 请求更新为
public static function RunCurlPostServices($url, $json)
{
$ch = curl_init(env('SERVICES_API_URL').$url);
curl_setopt($ch, CURLOPT_POST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
修复了问题。 这有帮助。感谢@Rezrazi 的努力
推荐阅读
- json - 为什么我从 mongodb 的 json 中的某些字段的值全为零?
- android - @Path 作为可选参数?
- angular - Angular:FileReader - 来自阅读器的访问列表
- android - weight=1 和 android:layout_width="0dp" 使我的视图消失
- javascript - 当我重新启动我的 node.js Web 服务器时,我的调用堆栈会发生什么?
- c# - 执行一个可能有一些参数为空的查询
- python - Jupyter Notebook 无法在命令行中运行代码
- python - 在开发过程中如何使用 Keras 获得可重现的结果?
- android - java.lang.NoClassDefFoundError 与 Kotlin 数据类
- vb.net - 显示新表单时的视觉基本问题