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

Laravel Passport报错:cURL error 7连接localhost:8080被拒绝

解决Laravel Passport本地调用连接拒绝问题

问题概述

通过Postman直接请求http://localhost:8080/oauth/token可正常获取令牌,但Laravel内部通过Guzzle发起请求时,出现以下错误:

Illuminate\Http\Client\ConnectionException: cURL error 7: Failed to connect to localhost port 8080 after 0 ms: Connection refused in file /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php on line 856

排查与解决步骤

1. 修正请求地址的网络指向

如果你的Laravel应用部署在Docker容器、虚拟机这类隔离环境中,容器内的localhost指向容器自身,而非宿主机的服务。需替换为宿主机的实际IP(如http://192.168.1.100:8080/oauth/token):

  • Docker环境(Windows/macOS)可使用host.docker.internal替代localhost;
  • Linux Docker需额外配置--add-host=host.docker.internal:host-gateway启动参数,再使用该地址。

2. 确认端口监听状态

在服务器终端执行以下命令,检查8080端口的监听情况:

netstat -tulpn | grep 8080

确保端口监听地址为0.0.0.0(允许内外访问),而非仅127.0.0.1(仅本地回环)。

3. 规范Guzzle请求参数格式

原代码未将请求参数放入form_params数组,Guzzle无法识别为表单提交,修正后的代码:

public function getTokenAndRefreshToken(OClient $oClient) {
    $http = new Client;
    
    $response = $http->request('POST', 'http://你的正确地址/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 20,
            'client_secret' => 'R9pywYcu9cRdRBJWv*********rJBwdSOSq',
            'username' => 'kh123@mail.com',
            'password' => "123456",
            'scope' => '*',
        ]
    ]);
    $result = json_decode((string) $response->getBody(), true);
    return response()->json($result, $this->successStatus);
}

4. 检查防火墙/安全组规则

确认服务器防火墙(如iptables、ufw)或云服务商安全组未拦截8080端口的内部访问流量。

5. 服务器内直接测试cURL

登录服务器终端执行以下命令,验证网络连通性:

curl -X POST http://localhost:8080/oauth/token -d "grant_type=password&client_id=20&client_secret=你的密钥&username=kh123@mail.com&password=123456&scope=*"

若此命令也报错,说明是网络配置问题;若成功,则排查Laravel应用的环境变量或Guzzle配置。

内容的提问来源于stack exchange,提问作者Tony nguyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:02:11