首页 > 解决方案 > 如何在 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);
}

我需要$dataAPI 端点返回的数据而不是布尔值。

标签: phppythonlaraveldjango-rest-framework

解决方案


为了让 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 的努力


推荐阅读