【问题标题】:Testing API call in laravel controller/view在 laravel 控制器/视图中测试 API 调用
【发布时间】:2019-05-19 01:58:34
【问题描述】:

我正在测试我在 Postman 和其他基于 API 构建的接口中工作的 API 调用,但我正试图在我的 laravel 站点中实际获取我的返回值。

应该很简单,我制作了一个非常简单的服务文件,它使用 guzzle 来获取 API url,并且我在那里有一个使用测试电子邮件、密码和客户端 ID 登录的功能(所有这些都可以在Postman等api接口)

我在 authController 中调用类和函数,然后在视图中返回函数调用,然后将其转储到视图中。

但是,目前我的页面转储为空。

这里有没有我遗漏的东西,可能在我的服务文件中。我认为这里不应该传递任何东西,但也许我忽略了更明显的东西。

授权.php

<?php
namespace App\Services\restAPI;

use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;


use Session;
use Exception;

class AuthService
{

    protected $baseurl;
    protected $guzzleClient;

    public function  __construct() {
        $this->baseurl = config('http://ip.address');
        $this->baseurl = rtrim($this->baseurl, '/') . '/';  // ensure trailing slash

        $this->guzzleClient = new \GuzzleHttp\Client(
            ['verify'   => config('app.ca_pem_file'),
             'headers'  => [
                    'Event-ID' => ACCESS_EVENT_ID
                ],
             'base_uri' => $this->baseurl
            ]
        );
    }

    public function loginGetToken(){
        $password = "password";
        $email = "test@thisAPI.com";
        $client_id = "0";

        $payload = (object)[
            'password'=>(string)$password,
            'email'=>(string)$email
        ];

        $retval = $this->post('login/?client_id='.$client_id,$payload);

        return $retval;
    }

    private function post($endpoint,$payload){

        $result = $this->guzzleClient->request('POST', $endpoint, ['json'=>$payload]);
        $body = $result->getBody();
        return  json_decode($body);
    }
}

AuthController.php

use Redirect;
use Illuminate\Http\Request;
use App\Services\restAPI\AuthService;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $authService = new AuthService();
        $login = $authService->loginGetToken();

         return redirect(route('auth.login'))
            ->with('login', $login)
    }

login.blade.php

<?php

    dd($login);

?>

【问题讨论】:

    标签: php laravel api


    【解决方案1】:

    由于您正在重定向,因此数据不能直接作为变量在视图中使用。它应该在会话中,所以你可以在你的视图中尝试这个:

    dd(session('login'));
    

    https://laravel.com/docs/5.7/redirects#redirecting-with-flashed-session-data

    【讨论】:

    • 嗯,这确实有道理,但似乎仍然显示为空
    • 有没有更好的方法来尝试返回并转储,只是为了测试它是否返回了我在通话中所期望的?这是一个 POST 函数,但我需要查看它的响应主体
    • 您可以在访问视图之前在控制器中进行转储。
    • 所以我认为这让我有所收获,但在我的页面错误中,现在它只显示我的 URL 和 /login/?client_id=0,但我没有看到有效负载已通过?
    • 不确定。你可以在 Authorize.php post() 方法中 dd($result) 看看你得到了什么。
    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 2014-08-06
    • 2014-03-04
    • 2021-08-29
    相关资源
    最近更新 更多