【问题标题】:Laravel guzzle request working on tinker but unauthorized in controllerLaravel guzzle 请求在修补程序上工作但在控制器中未经授权
【发布时间】:2018-08-22 16:37:18
【问题描述】:

我遇到了一个无法解决的问题,我有一个使用 Guzzle 连接到 RESTful api 的类,它在修补程序中工作,但在控制器中,我总是使用相同的连接得到 401 未经授权的错误数据。

ApiConnectionClass

use App\ApiData;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7;
class ApiConnectionClass
{
    var $conn_data;
    var $client;

public function __construct()
{
    $this->conn_data = ApiData::findOrFail(1);
    $this->client = new Client(['base_uri' => $this->conn_data->url]);
}

 public function lista_pruebas(){
    try{
        $response = $this->client->request('GET', 'pruebas/detalles', [
            'verify' => false,
            'headers' => ['Authorization' => 'Bearer ' . $this->conn_data->access_token],
        ]);
    } catch (GuzzleException $e) {
        dump(Psr7\str($e->getRequest()));
        if ($e->hasResponse()) {
            dd(Psr7\str($e->getResponse()));
        }
    }
     return json_decode($response->getBody()->getContents());
 }

在修补程序中我得到正确的 json 响应

$api = new App\Classes\ApiConnectionClass();
$api->lista_pruebas();

ApiController

use App\Classes\ApiConnectionClass;


class ApiController extends Controller
{
    public function lista_pruebas(){
        $api = new ApiConnectionClass();
        $lista = $api->lista_pruebas();

        return view('pruebas.index', compact('lista'));
    }
}

从控制器调用的 ApiConnectionClass 响应

""" HTTP/1.0 401 Unauthorized\r\n 日期:2018 年 8 月 22 日星期三 16:20:58 GMT\r\n 服务器:Apache/2.4.33 (Win64) PHP/7.2.4\r\n 变化: 授权\r\n X-Powered-By: PHP/7.2.4\r\n Cache-Control: no-cache, 私有\r\n 内容长度: 13\r\n 连接: 关闭\r\n 内容类型: 文本/html; charset=UTF-8\r\n \r\n 未经授权。 """

【问题讨论】:

  • 我的2cents英文码,对你有很大帮助。祝你好运!

标签: laravel guzzle


【解决方案1】:

这似乎不是您在代码中所做的错误,因为我可以在网络上随处看到 guzzle 的这种用法。不过,我确实有一些建议。 Tinker 使用与您的应用程序不同的运行时(分别为 php-cli 与 php-fpm),这可能会导致问题,因为在一种情况下(php-cli)php 直接从您的盒子进入 api 服务器,而在另一种情况下它会通过在发出请求之前您的网络服务器(php-fpm)。首先要做的是清除您的 laravel 缓存并使用 php artisan cache:clear 和 php artisan config:clear 进行配置,如果失败,我会查看您的 Web 服务器上的跨域限制或设置。祝你好运!

【讨论】:

  • 完美,你救了我的命,这是一个跨域问题
猜你喜欢
  • 2018-11-25
  • 1970-01-01
  • 2017-12-27
  • 2022-01-11
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
相关资源
最近更新 更多