Laravel 使用 post 从控制器调用内部 API,并将基本身份验证授权传递给请求

问题描述 投票:0回答:2

我正在从控制器调用内部 API 路由,但无法使用 laravel 8 设置标头

$request = Request::create('/api/login/', 'POST',['id' => '1']);
$request->headers->set('Authorization','Basic YWJjOjEyMw==');//not working

$response = Route::dispatch($request);

print_r($response);
php laravel routes laravel-8 laravel-routing
2个回答
0
投票

您是否尝试过使用

Http
外观来实现这一点?

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders(['Authorization' => 'Basic ...'])->post('/api/login');

$json = $response->json();
$specific_field = $response->json('specific_field');

0
投票

如果您想发送http请求,请尝试使用Guzzle HTTP客户端

如果它没有安装在你的 Laravel 项目中,请通过以下命令安装它:

composer require guzzlehttp/guzzle

http 获取示例:

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

$response = Http::post('http://example.com/users', [
   'name' => 'Steve',
   'role' => 'Network Administrator',
]);

欲了解更多信息,请访问 Laravel 文档 此处

注意:您应该提供完整的链接。就我而言,在本地和 Laragon 中。我提供以下网址

 myproject.test/user/activity.

所以在你的情况下考虑端口和路由 url。它可能是这样的:

localhost:8000/to/your/route
© www.soinside.com 2019 - 2024. All rights reserved.