laravel - laravel:登录到外部 API
问题描述
我第一次使用 laravel 来使用外部 api。我需要使用外部 api 进行身份验证,而不是使用 Laravel 身份验证。我已经使用 insomnia rest 客户端测试了端点,我得到了 200(OK),这很棒。为了在 Laravel 上完成它,我做了以下工作:
我还进口了:
use GuzzleHttp\Client;
我修改了文件中的 store 方法:app/Http/Controllers/Auth/AuthenticatedSessionController
并将 store 方法更改为
public function store(LoginRequest $request)
{
$client = new Client(['base_uri'=>'http://www.abcde.com']);
$response = $client->post('/api/token',['auth'=>[$request->input('email',$request->input('password'))]]);
dd(($response)->getStatusCode());
}
但我得到了错误:
未定义的偏移量:1
我现在被困住了,不完全确定该怎么做。
编辑 api 数据结构:
{
"email": "greentwigg@gmail.com",
"password": "Password0001",
}
解决方案
我要稍微修改一下你的代码。如果您需要包含标题,这是您需要采用的格式。
public function store(LoginRequest $request)
{
$client = new Client();
$response = $client->request('POST','http://www.abcde.com/api/token'),[
'json' => [
'email' => $request->input('email'),
'password' => $request->input('password'),
],
'headers' => [
'Content-Type' => 'application/json',
]
]);
dd(($response)->getStatusCode());
}