今天给大家分享,如何在laravel
中调用多个api
我们现在承诺可以从客户端调用多个 api(vue、react、js…)。如果你使用promise.all([…]),它会返回多个promise好吧,我们走
首先,可以安装laravel 11项目
第二个,我们可以在web.php或者controller,services,..
中设置示例:我在web.php文件中编写代码,帮忙测试一下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use illuminate\support\facades\http;
use guzzlehttp优质资源网点我wcqh.cn\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 re优质资源网点我wcqh.cnturn 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 ($res优质资源网点我wcqh.cnponse) {
// 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优质资源网点我wcqh.cn() ? $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时,它返回数据
好吧优质资源网点我wcqh.cn,或者你可以使用 http::pool ,请求 api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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://j优质资源网点我wcqh.cnsonplaceholder.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]->优质资源网点我wcqh.cnjson() : 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 请求
以上就是Laravel 中的多个 API 与 HTTP 请求的详细内容,更多请关注青狐资源网其它相关文章!
暂无评论内容