0
votes

Apparently, am able to consume my own API via Javascript using VueJs' Axios and jQuery's Ajax but the same has failed to work with Guzzle HTTP client.

How can I use the CreateFreshApiToken middleware with Guzzle.

Axios - Ok

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

Guzzle - Failed

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

1 Answers

1
votes

Well, createFreshApiTokens attaches a cookie for authorization, but when you are using guzzle you are not making a request from the client side ( browser ) so the cookie is not attached to the request!