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

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

显然,我可以使用VueJs的Axios和jQuery的Ajax通过Javascript使用我自己的API,但同样的方法却无法与Guzzle HTTP客户端一起使用。

如何在Guzzle中使用CreateFreshApiToken中间件。

值得 - 10月

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

Guzzle - 失败了

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()]);
}
ajax laravel axios guzzle laravel-passport
1个回答
1
投票

好吧,createFreshApiTokens附加一个cookie用于授权,但是当你使用guzzle时,你没有向客户端(浏览器)发出请求,因此cookie没有附加到请求!

© www.soinside.com 2019 - 2024. All rights reserved.