如何将中间件分配给特定的路由组? [英] How to assign a middleware to specific group of routes?

查看:49
本文介绍了如何将中间件分配给特定的路由组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个路由块,到目前为止我只知道中间件可以通过nuxt-config.js(全局)或每个路由(独立)进行分配

let's say I had this block of route, so far I only knew that middleware could be assigned through nuxt-config.js (globally) or per route (independently)

页面

 - index.vue
 - goSomeWhere.vue
 - goThisWay.vue
 - admin
    - index.vue
    - goThere.vue
    - goHere.vue

我想为每个 /admin 路由分配一个中间件,那么还有其他适合我的方法吗?

I want to assign a middleware just for every /admin routes, so is there another approach that might be suitable for me?

推荐答案

当然,验证路由块最简洁的方法是使用针对以/admin 开头的任何路由的全局中间件.

Certainly the most concise way to verify a block of routes is to use a global middleware that targets any route starting with /admin.

您可以在中间件文件夹中设置一个文件,根据条件定义您需要的重定向.显然,您想阻止未以管理员级别用户身份登录的人的任何管理员路由.为此,您应该为您的商店中的任何管理员用户设置一个属性,例如admin",或者如果您需要设置级别,您可以分配一个值 admin1、admin2 等.为了简单起见,假设任何登录的授权用户in 在商店的用户对象中设置了一个属性 admin = true; .

You could set up a file inside the middleware folder that defines the redirects you need depending on the conditions. Obviously you want to block any admin route from someone who isn't logged in as an admin level user. To do this you should set any admin user in your store with a property such as "admin" or if you need to set levels you could assign a value of admin1, admin2 etc. For the sake of simplicity lets say any authorized user who logs in has a property admin = true; set in their user object in the store.

然后你应该在中间件文件夹中创建一个文件,我们称之为'auth.js':

You should then create a file in the middleware folder, let's call it 'auth.js':

export default function ({store, redirect, route}) {

  const userIsAdmin = !!store.state.user.admin;
  const urlRequiresAuth = /^\/admin(\/|$)/.test(route.fullPath)
  if (urlRequiresAuth && !userIsAdmin) {
      return redirect('/')
  }
  return Promise.resolve
}

这只是检查用户是否将 admin 设置为 true 以及请求的路由是否需要身份验证.如果用户未经授权,它将重定向到您的索引页面.

This simply checks if the user has admin set to true and if the requested route requires auth. It will redirect to your index page if the user is not authorized.

您需要在 nuxt.config.js 中注册您的中间件文件:

You will need to register your middleware file in nuxt.config.js:

...

router: {
  middleware: ['auth'];
},

...

你应该没事了.

这篇关于如何将中间件分配给特定的路由组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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