laravel5.8/vue2.5/vuex3.1/axios0.19を使って楽天の書籍情報を取得・登録できるwebアプリケーションを作成中です。
相談したいのは、axiosでlaravel側の楽天ブックAPIの情報を取得するアクションを実行させる処理です。
【Laravel & Guzzle】APIの呼び出し方法をわかりやすく解説
こちらの記事内にあります、「【GET編】コントローラに処理を記載して、viewで表示する」を参考に実装しています。
・エラー内容
app.js:665 Uncaught (in promise) Error: Request failed with status code 500 at createError (app.js:665) at settle (app.js:911) at XMLHttpRequest.handleLoad (app.js:178)
500エラーについてログを確認したところ、以下の記述がありました。
[2020-01-16 19:39:49] production.ERROR: Object of class GuzzleHttp\Psr7\Response could not be converted to string {"userId":1,"exception":"[object] (ErrorException(code: 0): Object of class GuzzleHttp\Psr7\Response could not be converted to string at /home/engineer5271/op-book.tk/laravel/src/app/Http/Controllers/API/BookController.php:58) [stacktrace] #0 /home/ホスト/アプリドメイン/laravel/src/app/Http/Controllers/API/BookController.php(58): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(4096, 'Object of class...', '/home/ホスト...', 58, Array) #1 [internal function]: App\Http\Controllers\API\BookController->show('\xE4\xBF\xAE\xE7\xBE\x85\xE3\x81\xAE\xE9\x96\x80')
・やったこと
vueで作ったinputにテキストが入力されると、キーワードをURLパラメータに乗せてapiアクションのルートにGET。
コントローラーアクションとしては「show」になります。
・store/index.js内の該当メソッド
async doSearch({ commit }, queryWord) { // キーワードをリクエストパラメータで送る const url = `/book/${queryWord}`; // TODO:例外処理 const results = await axios.get(url); console.log(results); //データが返ってくるか確認 const data = results.data.Items; if (data.length < 1) { console.log("ヒットしませんでした"); //データが返ってくるか確認 commit("setErrState", true); commit("setResultMsg", "ヒットしませんでした"); } else { commit("setErrState", false); console.log("ヒット件数:" + data.length); //データが返ってくるか確認 commit("setResultMsg", data.length + "件ヒットしました"); } // mutationsを呼び、storeと同期する commit("setResults", data); } } });
・route/web.php内にapireourceルートを設置
Route::apiResource('/book', 'API\BookController');
・app\HttpディレクトリにAPI/BookControllerを作成
// 以下のターミナルコマンドを実行 php artisan make:controller API/BookController --api
・config/services.phpに環境変数(楽天ブックスのapplicationId)の記述を追加
return [ 'sparkpost' => [ 'secret' => env('SPARKPOST_SECRET'), ], // 末尾に追加 'rakuten' => [ 'api_key' => env("API_KEY"), 'secret_key' => env("SECRET_KEY"), 'affiliate_id' => env("AFFILIATE_ID") ] }
・コントローラー内に以下を記述
キーワード検索をしたいので、showアクションに記述
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use GuzzleHttp\Client; class BookController extends Controller { /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // GETで送られてきたキーワード $key_word = $id; // 取得件数 $limit = 10; // アプリケーションID(config/services.php/rakuten/api.keyを読み込む) $api_key = config('services.rakuten.api_key'); // 通信方法 $method = "GET"; // URL $url = "https://app.rakuten.co.jp/services/api/BooksBook/Search/20170404?format=json&formatVersion=2&elements=title,author,itemPrice,itemCaption,isbn,salesDate,largeImageUrl,booksGenreId,affiliateUrl&sort=standard&title={$key_word}&hits={$limit}&applicationId={$api_key}"; // リクエストインスタンス生成 $client = new Client(); // GETで楽天ブックスへ通信 $response = $client->request($method, $url); return response()->json($response); }
・php artisan route:list」で、ルートを確認
ここまでしたのですが、最初に挙げたエラーが解決できず詰まっています。
お手数かけますが、アドバイスをいただけると幸いです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。