首页 > 解决方案 > 使用 Symfony 客户端发出 localhost API 请求?

问题描述

我正在尝试使用 Symfony 5 对使用 API 平台开发的 API 发出请求。

有问题的 URL 是https://127.0.0.1:8000/api/cheeses

当我使用 Postman 对其进行 GET 请求时,一切正常。如果我要去浏览器中的 url,它可以工作。但是用 Symfony 用 PHP 发出请求是不可能的。我是这样去做的:

use Symfony\Contracts\HttpClient\HttpClientInterface;

class AbstractService
{

   public function __construct(private HttpClientInterface $client){}

   protected function request(string $method, string $path, array $params = [])
    {

        $response = $this->client->request('GET', 'https://127.0.0.1:8000/api/cheeses', [
            'headers' => [
                'Content-Type' => 'application/json',
            ]
        ]);

        dd(json_decode($response->getContent(), true, 512, JSON_THROW_ON_ERROR));
    }

}

当我尝试它循环时,我得到了错误:

“https://127.0.0.1:8000/api/cheeses”达到空闲超时。

但是,如果我尝试使用https://api.github.com/repos/guzzle/guzzle之类的外部 URL ,它就可以工作。

我的nelmio_cors配置:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['*']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/': null

任何想法 ?

标签: phpsymfonylocalhost

解决方案


推荐阅读