Laravel Passport为Guzzle HTTP Client创建新的API令牌

时间:2018-09-15 18:16:00

标签: ajax laravel axios guzzle laravel-passport

显然,能够使用VueJs的Axios和jQuery的Ajax通过Javascript使用我自己的API,但在Guzzle HTTP客户端上却无法使用。

如何在Guzzle中使用 CreateFreshApiToken中间件

Axios-确定

axios.get('api/user').then(response => {
    console.log(response.data);
}).catch(error => {
    console.log(error.response.data);
});

Ajax-确定

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()]);
}

1 个答案:

答案 0 :(得分:1)

好吧,createFreshApiTokens附加了一个cookie进行授权,但是当您使用guzzle时,您不是从客户端(浏览器)发出请求,因此该cookie不会附加到该请求!