Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Riotsmurf's avatar

Consuming my PASSPORT API with javascript not working. what am i missing?

I am trying to use the api i made inside vuejs when a user is logged in. (but also use the api outside the app) and i keep getting the 401 unauthorized error. I have followed a few guides and i cannot get it to work.

This is the Kernel.php:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
//             \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

        'api' => [
//            'throttle:60,1',
            'bindings',
        ],
    ];

As you can see i added the CreateFreshApiTokens::class to it.

config/auth.php:

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

routes/api.php:

Route::prefix('/samples')->group(function(){
        Route::get("/" ,"Api\SampleApiController@index");
        Route::get("/{sample_id}" ,"Api\SampleApiController@index");
        Route::post("/" ,"Api\SampleApiController@store");

        Route::get("/tests" ,"Api\SampleTestApiController@index");
        Route::post("/tests" ,"Api\SampleTestApiController@store");

        Route::get("/tests/analytes" ,"Api\SampleTestAnalyteApiController@index");
        Route::post("/tests/analytes" ,"Api\SampleTestAnalyteApiController@store");
    });

inside the controller _construct i am using $this->middleware('auth:api');

and this is my ajax:

axios.get('/api/v1/samples/5020122', {

                    params: {
                        get: "test",
                        find: "test"
                    }
                }).then(response => {
                    console.log(response);
                });

And its giving me a 401 response. I don't get it. Any ideas/questions would be super helpful.

0 likes
1 reply
aurawindsurfing's avatar

You need to add csrf headers to axios:

window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content');
};

and the same thing for ajax requests:

$.ajaxSetup({
  headers: {
   'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});

Hope it helps!

Please or to participate in this conversation.