[Nuxt.JS] доступ к объекту $ auth в контексте из плагина js - PullRequest
1 голос
/ 09 мая 2020

Я хочу получить доступ к объекту $ auth в контексте из js, определенного в 'plugins /', но не могу.


https://auth.nuxtjs.org/api/auth.html#auth

Этот модуль глобально внедряет экземпляр $ auth, что означает, что вы можете получить к нему доступ где угодно, используя this. $ Auth. Для плагинов asyncData, fetch, nuxtServerInit и Middleware вы можете получить доступ к нему из контекста. $ Auth


Это описано выше, но мой код (ax ios -interceptor. js) не может получить доступ к $ auth из контекста (он не определен). Что нужно для доступа к нему?

plugins / ax ios -interceptor. js

export default function (context) {
  const { $axios, route, redirect } = context

  $axios.interceptors.response.use(
    function (response) {
      return response
    },
    function (error) {
      const code = parseInt(error.response && error.response.status)
      const thisRoutePath = route.path

      if ([401, 403].includes(code)) {
        if (thisRoutePath !== '/') {
          redirect('/?login')
        }
      }
      return Promise.reject(error)
    }
  )
}

nuxt.config. js

export default {
  plugins: [
    '@/plugins/axios-interceptor.js'
  ],

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
    '@nuxtjs/auth'
  ],
  axios: {
    baseURL: BASE_URL
  },
  auth: {
    cookie: false,
    autoFetchUser: false,
    redirect: {
      login: '/login',
      logout: '/login',
      callback: '/callback',
      home: '/home'
    },
    strategies: {
      local: {
        endpoints: {
          login: { url: BACKEND_API_PATH_BASE + '/api/v1/login/', method: 'post', propertyName: 'token' },
          user: { url: BACKEND_API_PATH_BASE + '/api/v1/users/me', method: 'get', propertyName: false },
          logout: false
        },
      },
    }
  },
  router: {
    middleware: [
      'auth'
    ]
  },

Причина, по которой я хочу получить доступ к $ auth в axios-interceptor.js, заключается в том, что я хочу выполнить $ auth.logout () в блоке if ([401, 403].includes(code)) { и удалить токен.

1 Ответ

1 голос
/ 11 мая 2020

Теперь я могу получить доступ к $ auth, выполнив следующие действия:

export default {
  // plugins: [
  //   '@/plugins/axios-interceptor.js'  ########### REMOVE ###########
  // ],
    :
  (Ommit)
    :
  auth: {
      :
    (Ommit)
      :
    plugins: [
      '@/plugins/axios-interceptor.js'  // ########### ADD ###########
    ]
  },
  (Ommit)
      :
}

То, что мне нужно было сделать, было указано ниже.
https://auth.nuxtjs.org/recipes/extend.html

...