今天给大家分享,如何在Laravel中调用多个api
我们现在承诺可以从客户端调用多个 api(vue、react、js...)。如果你使用Promise.all([...]),它会返回多个promise
好吧,我们走吧
首先,可以安装项目Laravel 11
第二个,我们可以在web.php或控制器、服务中设置它,..
示例:我在web.php文件中编写代码,帮忙测试一下
use Illuminate\Support\Facades\Http; use GuzzleHttp\Promise\Utils; use GuzzleHttp\Exception\ConnectException; use Illuminate\Http\Client\Pool; Route::get('multiple-request', function() { $responses = Utils::all([ 'foo' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/1')->then(function ($response) { // you can check data, after then return it return $response; }), 'bar' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/2')->then(function ($response) { // you can check data, after then return it return $response; }), 'baz' => Http::async()->get('https://jsonplaceholder.typicode.com/todos/3')->then(function ($response) { // you can check data, after then return it return $response; }), ])->wait(); // you need check data here $fooOk = $responses['foo']->ok(); $barSuccessful = $responses['bar']->successful(); $connectionFailed = $responses['baz'] instanceof ConnectException; return [ 'foo' => $responses['foo']->ok() ? $responses['foo']->json() : 'Request to foo failed', 'bar' => $responses['bar']->successful() ? $responses['bar']->json() : 'Request to bar failed', 'baz' => $responses['baz']->ok() ? $responses['baz']->json() : 'Request to baz failed', ]; });
当您请求 url : http://127.0.0.1/multiple-request 时,它返回数据
好的,或者你可以使用 Http::pool ,请求 api
Route::get('multiple-request-using-pool', function() { $responses = Http::pool(fn (Pool $pool) => [ $pool->get('https://jsonplaceholder.typicode.com/todos/1'), $pool->get('https://jsonplaceholder.typicode.com/todos/2'), $pool->get('https://jsonplaceholder.typicode.com/todos/3'), ]); $responses[0]->ok(); $responses[1]->successful(); // Kiểm tra và lấy nội dung từ các phản hồi $data = [ 'todo_1' => $responses[0]->ok() ? $responses[0]->json() : 'Request to todo 1 failed', 'todo_2' => $responses[1]->successful() ? $responses[1]->json() : 'Request to todo 2 failed', 'todo_3' => $responses[2]->ok() ? $responses[2]->json() : 'Request to todo 3 failed', ]; return response()->json($data); });
返回数据:
文章:Laravel 中的多个 API 与 HTTP 请求
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3