Support the ongoing development of Laravel.io →
Session Authentication Requests

I am trying to get the tasks of the logged in user into a vuejs component via axios but I keep getting

POST http://localhost:8000/api/tasks 401 (Unauthorized)

Here's the routes from api.php:

`Route::group(['middleware' => 'auth:api'], function() {

Route::prefix('tasks')->group(function() {
    Route::post('/', 'TasksController@index');
    Route::post('{id}', 'TasksController@single');
    Route::post('new', 'TasksController@new');
});

});`

The index function of TasksController:

`public function index(Request $request) {

if ( $request->ajax() ) {
    return auth()->user()->tasks()->orderBy('name', 'ASC')->get();
}

return view('tasks.index')
            ->with('tasks', auth()->user()->tasks()->orderBy('name', 'ASC')->get());

}`

And the vuejs component:

`<template> <div> <ul> <li v-for="task in tasks" v-bind:key="task.id">{{ task.name }}</li> </ul> </div> </template>

<script> export default { data() { return { tasks: [], } }, created() { this.fetchTasks(); }, methods: { fetchTasks() { axios({ url: 'api/tasks', method: 'POST', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }).then(res => { this.tasks = res.data; }); } } } </script>`
Last updated 3 years ago.
0

If you're receiving 401 it means the token might not be sent in the axios request to API therefore the user is unauthorized to access the route. Check it out properly with the dev tools and see the headers and in the API if you're receiving

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.