@ideagood

Как получить авторизованного пользователя?

Я только начал изучать api в связке laravel + vue, и не могу разобраться как получить авторизованного пользователя. Я пробую это сделать во так:
Контроллер
public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials, true)) {
            return Auth::user();
        }
        throw ValidationException::withMessages([
            'errors' => ['Логин или пароль не совпадает']
        ]);
    }

api маршруты:
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Route::post('/login', [UserController::class, 'login']);

код в компоненте vue
<template>
    <div class="container">
                <form @submit.prevent>
                    <div class="form-group mt-3">
                        <label class="text-white" for="email">Email</label>
                        <input v-model="form.email" type="text" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="email">
                    </div>
                    <div class="form-group mt-3">
                        <label class="text-white" for="password">Пароль</label>
                        <input v-model="form.password" type="password" name="password" class="form-control" id="password" placeholder="Пароль">
                    </div>
                    <button @click="loginUser" type="submit" class="btn my-btn-color mt-3">Войти</button>
                </form>
    </div>
</template>
<script>
export default {
    name: "LoginPage",
    data() {
        return {
            form: {
                email: '',
                password: '',
            },
        }
    },
    methods:{
        async loginUser(){
            try {
                await axios.post('api/login', this.form)
                const response = await axios.get('api/user')
                alert(response.data)
                await this.$router.push({name: 'home'})
            } catch (e) {
                console.log(e)
                this.errors.push(e.response.data.errors)
            }
        },
    }
}
</script>

в логах 401 ошибка
Error: Request failed with status code 401
Что я делаю не так?
  • Вопрос задан
  • 154 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы