如何在 Nuxt.js 通用模式下再次使用中间件?

How to use middlewares one more time in Nuxt.js universal mode?

我有中间件,我需要在用户每次访问页面时检查他是否经过身份验证。现在看起来是这样的,只是为了确定它是否能够与 localStorage:

一起工作
export default function({ store, redirect, route }) {
  console.log('Here is auth middleware')
  console.log(localStorage.getItem('token'))
}
// nuxt.config.js
  plugins: [
    '~/plugins/test.client.js'
  ],

通常,此中间件必须与 localStorage 配合使用。 Here 我找到了我的问题的解决方案,但它只有效一次(来自文档):

In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes

所以,我需要创建这样的中间件,它只能在 特定页面 上工作,并且能够与 localStorageNuxt.js 一起工作应用处于 通用 模式。是否可以实施?

这个问题可以用mixins来解决。在 mixins/auth.js 我有这个代码:

import { verifyToken } from "@/api";
export default {
  async mounted() {
    if (!localStorage.getItem('token')) {
      await this.$router.push({path: '/login'})
    } else {
      const checkToken = await verifyToken({ token: localStorage.getItem('token') })
      if (checkToken.error) {
        localStorage.removeItem('token')
        await this.$router.push({path: '/login'})
      }
    }
  }
}

然后,在我需要检查 localStorage 中是否存在有效令牌的页面上,我只是这样做:

<script>
import auth from '~/mixins/auth'
export default {
  name: "Component",
  mixins: [auth],
</script>