Ajax Laravel Passport为Guzzle HTTP客户端创建新的API令牌
显然,我可以使用VueJs的Axios和jQuery的Ajax通过Javascript使用我自己的API,但Guzzle HTTP客户端却无法使用同样的API 如何在Guzzle中使用中间件 Axios-正常Ajax Laravel Passport为Guzzle HTTP客户端创建新的API令牌,ajax,laravel,axios,guzzle,laravel-passport,Ajax,Laravel,Axios,Guzzle,Laravel Passport,显然,我可以使用VueJs的Axios和jQuery的Ajax通过Javascript使用我自己的API,但Guzzle HTTP客户端却无法使用同样的API 如何在Guzzle中使用中间件 Axios-正常 axios.get('api/user').then(response => { console.log(response.data); }).catch(error => { console.log(error.response.data); }); Aja
axios.get('api/user').then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.response.data);
});
Ajax-OK
window.$.ajax({
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'GET',
url: 'api/user',
success: function (response) {
console.log(response);
},
error: function (xhr) {
console.error(xhr.responseText);
}
});
狂饮-失败
try {
$client = new Client([
'base_uri' => 'http://localhost/passport-test/public/api/',
'headers' => [
'Accept' => 'application/json',
],
]);
$api_response = $client->request('GET', 'user', ['debug' => true]);
$user = json_decode($api_response->getBody(), true);
return response()->json($user);
} catch (ConnectException $ex) {
return response()->json(['code' => $ex->getCode(), 'message' => $ex->getMessage()]);
} catch (ClientException $ex) {
return json_decode($ex->getResponse()->getBody(), true);
} catch (ServerException $ex) {
return response()->json(['code' => $ex->getCode(), 'message' => $ex->getMessage()]);
}
好的,
createFreshApiTokens
附加了一个cookie以进行授权,但是当您使用guzzle时,您没有从客户端(浏览器)发出请求,因此cookie没有附加到请求 啊。但我想知道如何使用guzzle实现同样的效果。现在,我必须像其他任何第三方应用程序一样使用自己的API。你需要将令牌放在标题中授权'=>'承载'+$token.或在cookie[laravel_token]中发送令牌。但是,在这种情况下为什么要使用cookie呢?web应用程序与应用程序源代码是分开的。“api.example.com”是api,“example.com”是web应用程序,您希望您的api使用cookies进行身份验证吗?