后端到后端 API 请求和响应

Back end to Back end API request and response

我有一个基于 laravel 8 构建的应用程序,前端为 Vue Spa,使用 Sanctum

我有一个控制器方法从另一个 Laravel 项目请求(使用它的 Sanctum API)所以基本上,Spa 请求来自 Laravel 1,它请求来自Laravel 2 项目。

根据 L2 项目的回复,L2 上的 Controller 方法是:

 public function popular(Request $request)
 {
    $limit = 20;
    if ($request->has('limit')) {
        $limit = $request->limit;
    }

    $perPage = 20;
    if ($request->has('per_page')) {
        $limit = $request->per_page;
    }

    if ($request->has('page')) {

        $articles = $request
            ->user()
            ->articles()
            ->activeArticles()
            ->select('articles.uuid', 'articles.title')
            ->orderBy('articles.views', 'DESC')
            ->simplePaginate($perPage);

    } else {

        $articles = $request
            ->user()
            ->articles()
            ->activeArticles()
            ->select('articles.uuid', 'articles.title')
            ->orderBy('articles.views', 'DESC')
            ->limit($limit)
            ->get();
    }

    return $articles;
}

此响应由 L1 Controller 方法接收,并像这样发送回 Spa:

public function popular(Request $request)
{
    $apiEndPoint = self::$apiBaseUrl . '/article/popular';

    $response = self::$httpRequest->get($apiEndPoint, $request->query());

    if (!$response->successful()) {
        return $this->setMessage(trans('help.api_error'))->send();
    }

    $body = $response->getBody();

    return response(['data' => $body]);
}

有了这个return:

    return response(['data' => $body]);

我得到并清空了数据对象:

{
    data: {}
}

然后 return:

   return response($body);

我将有效载荷作为文本/字符串获取:

[{"id":15,"uuid":"c6082143-0f34-443b-9447-3fa57ed73f48","name":"dashboard","icon":"database","active":1,"owned_by":2,"product_id":4,"created_at":"2021-12-23T11:46:35.000000Z","updated_at":"2021-12-23T11:46:35.000000Z"},{"id":16,

如何 return $body 和 JSON 一样去水疗中心?

更新:我尝试了下面的建议,但结果仍然是异常。

return response()->json($body);

Returns:

"message": "json_decode(): Argument #1 ($json) must be of type string, GuzzleHttp\Psr7\Stream given",

所以让正文进入 getBody() return 是一个我理解的字符串。

如果我记录 $body 我得到:

$body = $response->getBody();
Log::info($body);

[2021-12-25 23:15:36] local.INFO: {"current_page":2,"data":[{"uuid":"aa4a47bf-4975-4e78-868a-103398934504","title":"Ritchie-Hoeger"},

感谢您的帮助,祝节日快乐。

使用json辅助函数

    return response()->json($body);
or
    use Response;
    
    return Response::json($body);

这将创建 \Illuminate\Routing\ResponseFactory 的一个实例。请参阅 phpDocs 了解以下可能的参数:

/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response 
* @static 
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
   
    return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

我需要 ->getContents()->getBody()

之后
$body = $response->getBody()->getContents();

又好了...

API 响应者

首先在laravel中创建一个特征'app\Traits\ApiResponser.php'

<?php

namespace App\Traits;
use Carbon\Carbon;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

trait ApiResponser{

    public function  set_response($data, $status_code, $status, $details)
    {
        $resData = response(json_encode(
                [
                    'status'        =>  $status, // true or false
                    'code'          =>  $status_code,
                    'data'          =>  $data,
                    'message'       =>  $details
                ]
        ), 200)
        ->header('Content-Type', 'application/json');

        $data = [];

        return $resData;
    }

}

在任何控制器中第二次调用此特征的函数 set_response()

<?php
namespace App\Http\Controllers;

use App\Models\User;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;

class ListController extends Controller
{
    use ApiResponser;


    public function getAllUserList(Request $request)
    {
        $data = User::select('id', 'name', 'email')->get();
        return $this->set_response(['data' => $data], 200,'success', ['User list']);
    }


}


输出会像这样