【问题标题】:How to send a request to another controller in Laravel using Guzzle如何使用 Guzzle 向 Laravel 中的另一个控制器发送请求
【发布时间】:2020-01-27 01:22:03
【问题描述】:

我正在尝试使用 Guzzle 从模型向我的routes/web.php 中定义的路由发送 POST 请求。模型和控制器都定义在同一个 Laravel 应用程序中。链接到路由的控制器操作返回 JSON 响应,并且在使用 Ajax 从 javascript 调用时可以正常工作。但是,当我尝试使用 Guzzle 执行此操作时,出现以下错误:

GuzzleHttp \ Exception \ ClientException (419)
Client error: `POST https://dev.application.com/login` resulted in a `419 unknown status` response

在寻找解决方案时,我读到它可能是由于缺少 csrf 令牌引起的,所以我将它添加到我的请求中,但我仍然得到同样的错误。

这是使用 Guzzle 发送请求的模型代码:

$client = new Client();
$response = $client->post(APPLICATION_URL.'login', [
    'headers' => [
        'X-CSRF-Token' => csrf_token()
    ],
    'form_params' => [
        'socialNetwork' => 'L',
        'id_token' => $id
    ],
]);

APPLICATION_URL 只是应用程序的基本 URL,以 https:// 开头。

我错过了什么吗?提前致谢!

【问题讨论】:

    标签: php laravel laravel-5.6 guzzle


    【解决方案1】:

    不要在您的应用内部发送请求,而是通过将 post 请求发送到路由来转发呼叫

    这种方法似乎比使用像 Guzzle 这样的 HTTP 客户端库更快

    你的代码应该是这样的

    $request = Request::create(APPLICATION_URL . 'login', 'POST', [
            'socialNetwork' => 'L',
            'id_token' => $id
        ]);
    $request->headers->set('X-CSRF-TOKEN', csrf_token());
    $response = app()->handle($request);
    $response = json_decode($response->getContent(), true);
    

    更新

    您必须手动处理来自内部调度的路由的响应,这是一个开始的示例

    web.php

    use Illuminate\Http\Request;
    
    Route::get('/', function () {
        $request = Request::create('/test', 'POST', ['var' => 'bar']);
        $request->headers->set('X-CSRF-TOKEN', csrf_token());
        $response = app()->handle($request);
        $responseContent = json_decode($response->getContent(), true);
        return $responseContent;
    });
    
    Route::post('test', function () {
        $upperCaseVar = strtoupper(request()->var);
        return response(['foo' => $upperCaseVar]);
    });
    

    通过GET 请求访问/ 路由并从/test 获得响应,就好像它是POST 请求一样 Result

    {
       "foo": "BAR"
    }
    

    希望对你有帮助

    【讨论】:

    • Route::dispatch好像不存在,是Illuminate\Routing\Route里面的函数吗?
    • 不,它在Illuminate\Support\Facades\Route
    • 您的解决方案似乎有效,除了发布数据;它似乎在目标控制器动作中被忽略了。 $request->has('socialNetwork') 返回 false。
    • 你必须手动处理响应,我更新了我的答案
    猜你喜欢
    • 2020-07-14
    • 2018-03-21
    • 1970-01-01
    • 2019-01-09
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2021-12-28
    相关资源
    最近更新 更多