我有一个使用 Django rest 框架的 Django API 应用程序,它工作得很好。我有另一个应该使用 API 的 PHP laravel 应用程序。当我使用 curl 将数据发布到 API 端点时,数据被存储并返回一个对象。
我应该捕获这个对象并使用数据。但是,当我访问执行发布请求的路由时,返回的对象打印在页面上。
当我对应该包含返回数据的变量执行 dd($data) 时,我得到一个 bool 值(当数据成功发布时为 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 的 creatClient
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);
}
// 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_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"authorization: token *******"));
return curl_exec($ch);
}
我需要 $data 来获取 API 端点返回的数据,而不是 bool 值。
请您参考如下方法:
为了让 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);
}
解决了这个问题。 This帮助。 感谢@Rezrazi 的努力
