SPA vue前端和Laravel 7后端圣所 [英] SPA vue frontend and Laravel 7 backend Sanctum

查看:46
本文介绍了SPA vue前端和Laravel 7后端圣所的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Sanctum创建了一个vue和Laravel Spa,使用axios发送了请求,但是我的状态为204,当我尝试获取用户信息时,我得到了未经身份验证,我不知道这是怎么回事!

I created a vue and Laravel Spa using Sanctum , sent requests using axios but i get status 204 and when i tried to get user info i got Unauthenticated , i dont not know what is wrong !!

这是我的api.php

This is my api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

home.vue


<script>
import axios from "axios";
axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://localhost:8000/";

export default {
  name: "Home",
  methods: {
    login() {
      axios.get("/sanctum/csrf-cookie").then((response) => {
         axios.post('/login',{
           email:'user@user.com',
           password:'123456789'
         })
         .then(response=>{
           console.log(response)
         })
      });
    },
  },
};
</script>

dashboard.vue

dashboard.vue

<script>
import axios from "axios";
axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://localhost:8000/";

export default {
 mounted(){
     axios.get("/api/user").then((response)=>{
       console.log(response);
     })
 }
}
</script>

推荐答案

已解决!!!通过编辑Providers/RouteServiceProvider.php,将 mapApiRoutes 函数从中间件(['api'])更改为中间件(['web'])

SOLVED!!! By editing Providers/RouteServiceProvider.php, change mapApiRoutes function from middleware(['api']) to middleware(['web'])

protected function mapApiRoutes()
    {
        Route::prefix('api')
            ->middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));
    }

这篇关于SPA vue前端和Laravel 7后端圣所的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆