如何从我的 Laravel 控制器调用 API。 我的 laravel 运行在 127:0.0.1:8000 上。我的 api 也在这个端口运行 现在我想调用这个api
Route::get('/task/{task_id}', [TaskDetailsController::class, 'index']);
从我的网络控制器
这是我编写的调用该 API 的函数
public function index($task, $token)
{
$tokens = Token::where('token', $token)->first();
$tasks = Task::find($task);
$apiUrl = url('/api/task/'.$task);
if ($tokens && $tasks){
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
])->get(''.$apiUrl);
if ($response->successful()) {
dd($response->json());
} else {
dd("failed");
}
}
else{
dd("baal");
}
}
但我面临这个错误
cURL error 28: Operation timed out after 30002 milliseconds with 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://localhost:8000/api/task/11
我尝试编写原始 php 代码并使用 guzzle http 包 但没有得到修复。
控制器中的索引函数需要两个参数($tasks 和 $tokens);因此,您的 API 端点必须包含两个参数(task_id 和 token)。因此,您必须更改代码,如下所示:
Route::get("/index/{task_id}/{token}", [TaskDetailsController::class, "index"]);
完成这些更改后,您必须在 URL 中输入两个参数(task_id 和 token)(例如,“http://127.0.0.1:8000/2/your_token”。)。