首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue Router和Laravel Middleware

Vue Router和Laravel Middleware
EN

Stack Overflow用户
提问于 2018-09-27 01:47:42
回答 1查看 2.4K关注 0票数 4

我的应用程序有不同的路径:

代码语言:javascript
复制
GET /game/{any}

此路由受Laravel身份验证中间件保护。在此Laravel路由中,我希望构建SPA并提供Vue路由器:

代码语言:javascript
复制
const routes = [
  { path: '/game/start', component: GameStart },
  { path: '/game/stats', component: GameStats }
]

我有不受任何Laravel中间件保护的“main”路由

代码语言:javascript
复制
GET /{any}

整个Vue路由器看起来像这样:

代码语言:javascript
复制
const routes = [
      // Not protected URLs
      { path: '/', component: Main },
      { path: '/news', component: News },

      // Protected URLs
      { path: '/game/start', component: GameStart },
      { path: '/game/stats', component: GameStats }
    ]

所以我的问题是:像这样将后端和前端混合在一起是个好主意吗?因为我假设'/game/*‘路由器在前端部分不受保护。

或者我应该在前端使用Laravel Passport和token auth?

EN

回答 1

Stack Overflow用户

发布于 2018-12-11 06:38:44

您应该在前端使用Laravel Passport和令牌身份验证,并使用vue-router meta和callback (beforeEach)。

routes.js

代码语言:javascript
复制
...

export const routes = [
  { path: '/game/start', component: GameStart, meta: { requiresAuth: true } },
  { path: '/game/stats', component: GameStats, meta: { requiresAuth: true } },
  { path: '/signin', component: SigninPage },
  { path: '*', redirec: '/' }
];

router.js

代码语言:javascript
复制
import VueRouter from 'vue-router';
import { routes } from './routes';
import store from './store'

export const router = new VueRouter({
  routes,
  mode: 'history'
});

router.beforeEach((to, from, next) => {
  // you could define your own authentication logic with token
  let isAuthenticated = store.getters.isAuthenticated

  // check route meta if it requires auth or not
  if(to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
          path: '/signin',
          params: { nextUrl: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52523478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档