首页 > 解决方案 > Laravel - Guzzle 调用 POST 返回 GET

问题描述

我正在尝试在 Guzzle 中发出 POST 请求,但我正在调用的 API 正在返回响应,就好像我发出了 GET 请求一样。

控制器

class Controller extends BaseController
{
    const URL = 'http://apidomain.com';

    public function __construct()
    {
        $this->client = new \GuzzleHttp\Client();
    }

    public function createItem()
    {
        $body = [
            'itemId' => 123,
        ];

        $this->callPostRequest('api/items', $body);
    }

    private function callPostRequest($endpoint, $body)
    {
        $response = $this->client->post(self::URL.$endpoint, [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => "Bearer {$this->getAccessToken()}",
            ],
            'form_params' => $body
        ]);

        dd(\GuzzleHttp\json_decode((string) $response->getBody()));
    }
}

提供者

class ApiServiceProvider extends BaseServiceProvider
{
    public function boot()
    {
        $this->loadViewsFrom(__DIR__.'/../Views', 'api');
        parent::boot();
    }

    public function routes()
    {
        $group = [
            'prefix' => '/api',
            'namespace' => 'Api\Controllers',
        ];

        Route::group($group, function () {
            Route::get('/create-item', 'Controller@createItem')
                ->name('api::create-item');
        });
    }
}

后端点应该允许我添加一个项目;但是它没有添加,只是返回当前持久的项目列表。

标签: phplaravelguzzle

解决方案


推荐阅读