Hi!
Making a Laravel application using Laravel 12.x and Vue3
Have big problem with -> Route::middleware('auth:sanctum')
api.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\ChurchController;
use Illuminate\Support\Facades\Auth;
use Laravel\Sanctum\PersonalAccessToken;
use App\Models\User;
use Illuminate\Http\Request;
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->apiResource('churches', ChurchController::class);
Route::middleware('auth:sanctum')->get('/me', function () {
return response()->json([
'user' => auth()->user()
]);
});
Route::get('/ping', function () {
return ['status' => 'API works'];
});
Dashboard.vue
<template>
<h4>DASHBOARD</h4>
<div v-if="user">
<pre>{{ user }}</pre>
<div v-if="hasRole('admin')">Admin panel</div>
<div v-if="hasRole('prayer')">Forbeder panel</div>
<div v-if="hasRole('user')">Book forbønn</div>
</div>
<div v-else>
<h4>Ingen rolle 4</h4>
</div>
</template>
<script setup>
// console.log(
// "GLOBAL AXIOS AUTH:",
// axios.defaults.headers.common["Authorization"]
// );
// console.log("LOCAL STORAGE TOKEN:", localStorage.getItem("token"));
import { ref, onMounted } from "vue";
//import axios from "axios";
const user = ref(null);
onMounted(async () => {
const res = await axios.get("/me");
user.value = res.data;
});
const hasRole = (role) => {
if (!user.value || !user.value.roles) return false;
return user.value.roles.some((r) => r.slug === role);
};
</script>
Login.vue
<template>
<div>
<h2>Login</h2>
<input v-model="email" placeholder="Email" />
<br /><br />
<input type="password" v-model="password" placeholder="Passord" />
<br /><br />
<button @click="login">Login</button>
</div>
</template>
<script setup>
import { ref } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
const email = ref("");
const password = ref("");
const router = useRouter();
const login = async () => {
try {
const res = await axios.post("/login", {
email: email.value,
password: password.value,
});
localStorage.setItem("token", res.data.token);
axios.defaults.headers.common[
"Authorization"
] = `Bearer ${res.data.token}`;
console.log("LOGGET INN");
router.push("/dashboard");
} catch (e) {
alert("Feil innlogging");
}
};
</script>
Problem:
After Login, it call Dashboard
But when /api/me is executed the server shut down
Get this error in console
Login.vue:37 [Vue warn]: Unhandled error during execution of mounted hook
at <Dashboard onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref<
Proxy(Object) {__v_skip: true}
> >
at <RouterView>
at <App>
Dashboard.vue:33
GET http://127.0.0.1:8000/api/me net::ERR_EMPTY_RESPONSE
favicon.ico:1
GET http://127.0.0.1:8000/favicon.ico net::ERR_CONNECTION_RESET
axios.js?v=bbf5963d:1669 Uncaught (in promise) AxiosError: Network Error
at async newFunction (Dashboard.vue:33:16)
at async Dashboard.vue:29:17
Please help