我有一個laravel 8使用Vue Spa前端構建的應用程式,使用Sanctum.
我有一個控制器方法,它從另一個Laravel專案(使用它的SanctumAPI)請求,所以基本上,來自 Laravel 1 的 Spa 請求,它從 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 控制器方法接收,并像這樣發送回 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 response(['data' => $body]);
我得到并清空資料物件:
{
data: {}
}
有了這個回報:
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,
如何將$bodyJSON 格式回傳到 Spa?
更新:我嘗試了下面的建議,但結果仍然是例外。
return response()->json($body);
回傳:
"message": "json_decode(): Argument #1 ($json) must be of type string, GuzzleHttp\\Psr7\\Stream given",
所以讓身體getBody()回傳一個我理解的字串。
如果我記錄 $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"},
感謝您的幫助和節日快樂。
uj5u.com熱心網友回復:
使用 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);
}
uj5u.com熱心網友回復:
我需要->getContents()在->getBody()
$body = $response->getBody()->getContents();
一切又好了...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394020.html
上一篇:如何使用js引數呼叫Php函式
下一篇:列出沒有唯一列的資料框
