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

Laravel 10项目网页调用内部API出现超时问题求助

Laravel项目内部调用API超时问题解决

问题原因

你用php artisan serve启动的开发服务器是单线程的,当网页控制器发起HTTP请求调用本地API时,服务器正忙着处理网页请求,没法同时响应API请求,导致请求阻塞超时。

解决方案

方案1:直接复用业务逻辑(推荐)

没必要通过HTTP请求绕一圈,直接在网页控制器里调用获取用户的逻辑,或者抽成公共服务类复用代码:

抽成公共服务类

创建app/Services/EmployeeService.php:

namespace App\Services;

use App\Models\Employee;

class EmployeeService
{
    public function getAllEmployees()
    {
        return Employee::all();
    }
}

修改API控制器:

public function index()
{
    $employees = app(\App\Services\EmployeeService::class)->getAllEmployees();
    return response()->json($employees);
}

修改网页控制器:

public function index()
{
    $employees = app(\App\Services\EmployeeService::class)->getAllEmployees();
    // 后续直接用$employees渲染页面
    return view('users.list', ['employees' => $employees]);
}

直接调用API控制器方法(快速临时方案)

public function index()
{
    $apiController = new \App\Http\Controllers\Api\EmployeeController(); // 替换成你的API控制器实际路径
    $response = $apiController->index();
    $employees = $response->original; // 取出响应里的原始数据
    return view('users.list', ['employees' => $employees]);
}

方案2:启动多端口开发服务器(保留HTTP调用的情况)

如果一定要通过HTTP调用API,需要启动两个独立的开发服务器实例:

  • 第一个终端启动网页服务:php artisan serve --port=8000
  • 第二个终端启动API服务:php artisan serve --port=8001

然后修改网页控制器的请求地址:

public function index()
{
    $response = Http::get('127.0.0.1:8001/api/users');
    return $response->successful();
}

额外提示

你的API代码里有拼写错误:$emplyopees应该是$employees,虽然不影响功能,但建议修正避免后续维护问题。

内容的提问来源于stack exchange,提问作者Lovepreet Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:42:36