You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一Laravel项目中从WebController向ApiController发起API请求?

问题解决:WebController调用本地API超时

问题根源

你用php artisan serve启动的Laravel服务是单线程的——当WebController的profile方法发起HTTP请求到本地8000端口时,当前请求已经占用了唯一的线程,导致API请求无法被处理,最终超时。而Postman/浏览器直接访问是新的独立请求,所以能正常响应。

解决方案

方案1:直接调用控制器方法(最优)

既然两个控制器同属一个项目,完全没必要走HTTP请求,直接调用ApiController的方法即可:

use App\Http\Controllers\ApiController;

public function profile()
{
    $apiController = new ApiController();
    $response = $apiController->profile();
    
    // 直接返回响应,或者输出内容
    return $response;
    // 或者 echo $response->getContent();
}

也可以用依赖注入简化:

use App\Http\Controllers\ApiController;

public function profile(ApiController $apiController)
{
    return $apiController->profile();
}

方案2:使用多线程服务(必须走HTTP时用)

如果一定要通过HTTP调用,需要替换单线程的开发服务器:

  • 用Laravel Valet(Mac)或Homestead,这类工具默认用多线程服务器
  • 部署到Nginx/Apache环境,支持并发请求
  • 临时方案:启动两个不同端口的服务,比如第一个终端跑php artisan serve --port=8000,第二个终端跑php artisan serve --port=8001,然后WebController里请求http://127.0.0.1:8001/api/v1/profile

方案3:临时调整超时(不推荐)

这个只能暂时看到错误信息,解决不了根本问题,但可以用来验证:

try {
    $response = Http::timeout(2)->get($apiURL);
} catch (\Illuminate\Http\Client\ConnectionException $e) {
    dd($e->getMessage());
}

内容的提问来源于stack exchange,提问作者Alex Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:43:15