Skip to content
Advertisement

How to consume an authenticated API with Axios

I’m trying to build an application using Vue and Laravel. I currently use passport authentication within Laravel for user authentication. However, when I try to make a post request from a vue component using axio, I get 401 unauthorized, even if I am currently logged in.

Here is some example code:

1. Get request from the vue component

    getEvents() {
      axios
        .get("/api/calendar")
        .then(resp => (this.events = resp.data.data))
        .catch(err => console.log(err.response.data));
    }

2. Laravel routes

Route::apiResource('/calendar', 'CalendarController')->middleware('auth:api');

3. Calendar controller associated with the get request above

    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        return CalendarResource::collection(Calendar::all());
    }

I’ve spent hours with this issue and everything I have found simply doesn’t work. So any help at all is extremely appeciated.

edit:

Extra details

I am using Laravel 5.8.35.

In regards to passport, I am using this documentation laravel.com/docs/5.8/passport and followed the installationm front end quick start and deploying steps.

second edit:

Full code on github

Here is the full project on github incase this can help. https://github.com/CMHayden/akal.app/tree/feature/Calendar

Advertisement

Answer

I made some changes to your project, here is the github repository https://github.com/AzafoCossa/ProFix, hope it works.

Open AuthServiceProvider.php file, add Passport::routes() to boot() function and open auth.php file, update ‘api’ guard from 'driver'=>'token' to 'driver'=>'passport' and finally open Kernel.php file, add this middleware:

'web' => [
   // Other middleware...
   LaravelPassportHttpMiddlewareCreateFreshApiToken::class,
],
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement