0
votes

Trying to do a GET request to get all users from the DB inside an Vue component(laravel SPA) with axios will return just the document markup, no users or any type of error.

When I remove the web route it will return a page with the json data so the controller works for what I can see.

routes/web.php

Route::get('/{any}', function () {
   return view('layouts.vue');
})->where('any', '.*');

routes/api.php

Route::get('users', [UserController::class, 'index']);

usercontroller.php

class UserController extends Controller
{

    public function index()
    {
        $users = User::all();
        return response()->json($users);
    }

}

component.vue

export default {
    data(){
        return{
            users: [],
        }
    },
    created() {   
       axios.get('/api/users')
       .then(response => {
       this.users = response.data;
          console.log(response.data)
      });    
    },
}

Output

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="DHFuMQr5hPp5e0Y4KtCVJPG3NgSgbKOfSOiZFUvO"/>
    <title>Laravel SPA</title>
    <link href="http://localhost:8000/css/app.css" rel="stylesheet">
</head>

<body>
    <div id="app"></div>

    <script src="http://localhost:8000/js/app.js"></script>
</body>
</html>
1
you should exclude the 'api' endpoint from {any} route matching . here is an example: stackoverflow.com/questions/37542610/…Igor Moraru
I would say post this as an answer and i will check this as solution as this works....many thanks :-)user759235
I'm not sure. I've just spotted the problem, but solutions to this problem are quite a handful on SO. A link to one of them I think is sufficient in this situation. Thanks, anyway :)Igor Moraru

1 Answers

0
votes

Set the header "Content-Type" to "application/json" that way it expects json to be returned from the request and will handle it differently.

axios.get('/api/users',
   headers: {
        'Content-Type': 'application/json',
    }
});